C - Program to Implement Producer-Consumer Problem
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#define SIZE 10
main()
{
pid_t pid;
ssize_t byte;
char bin[SIZE], bout[SIZE];
int fields[2],ch=0,count = 0,a;
pipe(fields);
pid = fork();
if(pid==0)
{
xyz:
printf("\n\tEnter your choice:\n\t1.Producer,\n\t2.Consumer,\n\t3.Exit.");
printf("\n\tEnter Your choice: ");
scanf("%d",&ch);
if(ch==1)
{
close(fields[0]);
while(count<SIZE)
{
printf("\n\tEnter the string: ");
gets(bin);
write(fields[1], bin, SIZE);
count++;
}
close(fields[1]);
printf("\n\tPipe is full.");
goto xyz;
}
else
wait(0);
if(ch==3)
exit(0);
}
else
{
close(fields[1]);
wait();
printf("\n\tThe string is: ");
count=0;
while(count++<SIZE)
{
byte = read(fields[0], bout, SIZE);
if(byte!=0)
{
printf("\t");
puts(bout);
}
else
{
printf("\n\tSTRING IS EMPTY");
goto xyz;
}
sleep(1);
}
count=0;
goto xyz;
}
}
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#define SIZE 10
main()
{
pid_t pid;
ssize_t byte;
char bin[SIZE], bout[SIZE];
int fields[2],ch=0,count = 0,a;
pipe(fields);
pid = fork();
if(pid==0)
{
xyz:
printf("\n\tEnter your choice:\n\t1.Producer,\n\t2.Consumer,\n\t3.Exit.");
printf("\n\tEnter Your choice: ");
scanf("%d",&ch);
if(ch==1)
{
close(fields[0]);
while(count<SIZE)
{
printf("\n\tEnter the string: ");
gets(bin);
write(fields[1], bin, SIZE);
count++;
}
close(fields[1]);
printf("\n\tPipe is full.");
goto xyz;
}
else
wait(0);
if(ch==3)
exit(0);
}
else
{
close(fields[1]);
wait();
printf("\n\tThe string is: ");
count=0;
while(count++<SIZE)
{
byte = read(fields[0], bout, SIZE);
if(byte!=0)
{
printf("\t");
puts(bout);
}
else
{
printf("\n\tSTRING IS EMPTY");
goto xyz;
}
sleep(1);
}
count=0;
goto xyz;
}
}