I have to write a program where the producer gets the some number of inputs from the user and the consumer takes from the shared memory and prints their squares.In my program i have the shared memory size as 5.
my program works perfectly in the area that producer and consumer access the shared memory mutually but when i give the number of inputs as more than 5 ...the prducer is not waiting. Also after creating the shared memory ,when i run the consumer it is also not waiting...
Actually,at one point of time i got the answer..but after one day or two the same program is showing different result.My program is as below...please help
//header file
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<sys/sem.h>
#define MUTEX 0
#define FULL 1
#define EMPTY 2
#define KEY1 2019
#define KEY2 6000
struct sembuf sop;
int n;
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *_buf;
}s;
void wait(int sem_num,int semid);
void signal(int sem_num,int semid);
//implementation file
#include"pro_cons.h"
void wait(int sem_num,int semid)
{
sop.sem_op=-1;
sop.sem_num=sem_num;
sop.sem_flg=SEM_UNDO;
semop(semid,&sop,1);
}
void signal(int sem_num,int semid)
{
sop.sem_op=1;
sop.sem_num=sem_num;
sop.sem_flg=SEM_UNDO;
semop(semid,&sop,1);
}
//Producer
#include"pro_cons.h"
main()
{
int *data,c,sid,semid,i=0,a,b,in=0;
printf("\nEnter the number of elements");
scanf("%d",&n);
sid=shmget(KEY1,5*sizeof(int),IPC_CREAT|IPC_EXCL|00666);
if(sid==-1)
{
printf("Error in shared memory\n");
exit(1);
}
printf("got shared memory\n");
data=shmat(sid,0,00400);
semid=semget(KEY2,3,00666);
s.val=1;
semctl(semid,MUTEX,SETVAL,s);
s.val=0;
semctl(semid,FULL,SETVAL,s);
s.val=5;
semctl(semid,EMPTY,SETVAL,s);
/* printf("\n\nEnter the values:");*/
do
{
wait(EMPTY,semid);
wait(MUTEX,semid);
printf("Enter the %dst value",i+1);
scanf("%d",&data[in]);
signal(MUTEX,semid);
signal(FULL,semid);
in=(in+1)%5;
i++;
}while(i<n);
a=shmdt(data);
b=shmctl(sid,IPC_RMID,0);
}
/*CONSUMER*/
#include"pro_cons.h"
main()
{
int *data,sid,temp,i=0,semid,out=0;printf("initialized\n");
sid=shmget(KEY1,5*sizeof(int),00666);printf("getting shared mem\n");
if(sid==-1)
{
printf("Error in shared memory\n");
exit(1);
}
printf("got shared memory%d\n",sid);
data=shmat(sid,0,00400);
semid=semget(KEY2,3,00666);
printf("semid%d",semid);
do
{
wait(FULL,semid);
wait(MUTEX,semid);
printf("In critical section%d\n",data[out]*data[out]);
signal(MUTEX,semid);
signal(EMPTY,semid);
out=(out+1)%5;
i++;
}while(i<n);
}