Producer Consumer Program Source Code C
Header.h ex1:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<sys/stat.h>
#define N 5
#define n1 3
#define MUTEX 1
#define FULL 0
#define EMPTY 5
#define SHM_KEY 502
#define SHM_KEY1 909
#define SEM_KEY 703
Common to pro & cons
int semId,shmId;
union semun
{
int val;
struct
semid_ds *buf;
unsigned short
*array;
};
void wait(int semNo)
{
struct sembuf s;
s.sem_num=semNo;
s.sem_op=-1;
s.sem_flg=SEM_UNDO;
int r=semop(semId,&s,1);
if(r==-1)
{
perror("ERROR:
Semop()"); exit(1);
}
}
void signal(int semNo)
{
struct sembuf s;
s.sem_num=semNo;
s.sem_op=1;
s.sem_flg=SEM_UNDO;
int r=semop(semId,&s,1);
if(r==-1)
{
perror("ERROR:
Semop()"); exit(1);
}
}
Producer:
int initialize(int semNo,int value)
{
union semun u;
u.val=value;
int
r=semctl(semId,semNo,SETVAL,u);
if(r==-1)
{
perror("ERROR:
Semctl()");
exit(1);
}
}
int main()
{
int
*buffer,in=0,x=0,i;
struct
shmid_ds *data;
shmId=shmget(SHM_KEY,N*sizeof(int),0777|IPC_CREAT);
semId=semget(SEM_KEY,3,0777|IPC_CREAT);
if(shmId==-1)
{
perror("ERROR:
shmget()"); exit(0);
}
if(semId==-1)
{
perror("ERROR:
shmget()"); exit(0);
}
buffer=(int*)shmat(shmId,0,0777);
if(buffer==-1)
{
perror("ERROR:
shmat()"); exit(0);
}
initialize(MUTEX,1); initialize(FULL,0); initialize(EMPTY,5);
printf("Produced
elements are");
for(i=0;i<20;i++)
{
if(in<5)
{
x+=1;
wait(EMPTY); wait(MUTEX);
buffer[in]=x; printf("\n%d",x);
signal(MUTEX); signal(FULL);
in=(in+1)%N; sleep(1);
}
}
}
Consumer
int main()
{
int *buffer,out=0,x,i;
int output;
struct shmid_ds *data;
shmId=shmget(SHM_KEY,N*sizeof(int),0777|IPC_CREAT);
semId=semget(SEM_KEY,3,0777|IPC_CREAT);
if(shmId==-1)
{
perror("ERROR:
shmget()");
exit(0);
}
if(semId==-1)
{
perror("ERROR:
shmget()");
exit(0);
}
buffer=(int*)shmat(shmId,0,0777);
if(buffer==-1)
{
perror("ERROR:
shmat()");
exit(0);
}
for(i=0;i<20;i++)
{
if(out<5)
{
wait(FULL);
wait(MUTEX);
output= buffer[out];
printf("\nConsumed %d",output);
signal(MUTEX);
signal(EMPTY);
out=(out+1)%N;
}
}
}