Issue
I have challenge to implement two task using named pipes in C:
- Multiple producer - single consumer
- Single producer - multiple consumer
I already did single producer - single consumer problem but I'm not sure how can I start solving above tasks, can you advice me in that by recomanding suitable approach and methods?
Here is my single producer - single consument code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
const int dataAmountToProduce = 10;
int value = 0;
int const buforSize = 50;
void processProducer()
{
int savePipe;
while (value < dataAmountToProduce)
{
savePipe = open("pipe", O_WRONLY);
value++;
char str[buforSize];
sprintf(str, "%d", value);
printf("Producer %d produces value: %s\n", getpid(), str);
write(savePipe, str, buforSize);
if (value == dataAmountToProduce)
{
break;
}
}
close(savePipe);
}
void processConsumer()
{
int readPipe;
while (value < dataAmountToProduce)
{
readPipe = open("pipe", O_RDONLY);
char buf[buforSize];
read(readPipe, buf, buforSize);
printf("Consumer %d consumes value: %s\n", getpid(), buf);
value = atoi(buf);
if (value == dataAmountToProduce)
{
break;
}
}
close(readPipe);
}
main()
{
mkfifo("pipe", 0600);
if (fork() == 0)
{
printf("Creating producer process %d\n", getpid());
processProducer();
printf("Producer process %d finished work\n", getpid());
exit(0);
}
if (fork() == 0)
{
printf("Creating consumer process %d\n", getpid());
processConsumer();
printf("Consumer process %d finished work\n", getpid());
exit(0);
}
wait(NULL);
printf("Both child processes of process %d finished work.\n", getpid());
exit(0);
}
Solution
OK, I found a solution myself in both cases I added this block to producer method:
if (value == valuesAmountToProduce)
{
printf("Producent process %d sent END signal\n", getpid());
for (int i = 0; i <= amountOfConsumers; i++)
{
write(savePipe, "END", wielkoscBufora);
}
In consumer code I'm checking if passed value is END, if yes then I'm breaking a loop:
if (strcmp(buf, "END") == 0)
{
printf("Consumer process %d recived END signal\n", getpid());
break;
}
And I solved my problem in this way, for multiple producer - single consumer we can omit consumer loop as it is in first code snippet because there will be only one consumer.
Answered By - Kamil W