Monday, June 16, 2014

IMPLEMENTING PRODUCER-CONSUMER SYSTEM


C program that implements a producer-consumer system with two processes
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUFFER 3
int produceItem();
int child_pid;
int buffer[MAX_BUFFER],item;
int fillCount = 0; // items produced
int emptyCount = MAX_BUFFER; // remaining space
void producer()
{
while (1)
{
item = produceItem();
if(item==0)
return;
if(emptyCount==0)
{
printf("\nbuffer full");
break;
}
emptyCount--;
buffer[emptyCount]=item;
printf("\n %d put into the buffer..",item);
fillCount++;
}
return;
}
void consumer()
{
while (1)
{
if(fillCount==0)
{
printf("\nbuffer empty");
break;
}
fillCount--;
item=buffer[emptyCount];
printf("\n %d removed from buffer..",item);
emptyCount++;
printf("\n %d consumed..",item);
}
}
int produceItem()
{
int n;
printf("\n Enter the number for production (0 to stop)..\n");
scanf("%d",&n);
return n;
}
int main()
{
char i;
while(i!='y' && i!='Y')
{
producer();
consumer();
printf("\nDo you want to exit...(Y or N)....");
scanf("%c",&i);
}
}
output:-
Image

0 comments:

Post a Comment