C中命名管道的消费者-生产者问题



我面临着在C:中使用命名管道实现两个任务的挑战

  • 多生产者-单一消费者
  • 单个生产者-多个消费者

我已经解决了单一生产者-单一消费者的问题,但我不确定如何开始解决上述任务,你能建议我重新要求合适的方法和方法吗?

这是我的单一生产者-单一消费者代码:

#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: %sn", 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: %sn", getpid(), buf);
value = atoi(buf);
if (value == dataAmountToProduce)
{
break;
}
}
close(readPipe);
}
main()
{
mkfifo("pipe", 0600);
if (fork() == 0)
{
printf("Creating producer process %dn", getpid());
processProducer();
printf("Producer process %d finished workn", getpid());
exit(0);
}
if (fork() == 0)
{
printf("Creating consumer process %dn", getpid());
processConsumer();
printf("Consumer process %d finished workn", getpid());
exit(0);
}
wait(NULL);
printf("Both child processes of process %d finished work.n", getpid());
exit(0);
}

好吧,我自己在这两种情况下都找到了解决方案,我将这个块添加到生产者方法中:

if (value == valuesAmountToProduce)
{
printf("Producent process %d sent END signaln", getpid());
for (int i = 0; i <= amountOfConsumers; i++)
{
write(savePipe, "END", wielkoscBufora);
}

在使用者代码中,我检查传递的值是否为END,如果是,则我将打破一个循环:

if (strcmp(buf, "END") == 0)
{
printf("Consumer process %d recived END signaln", getpid());
break;
}

我用这种方式解决了我的问题,对于多个生产者-单个消费者,我们可以像第一个代码片段中那样省略消费者循环,因为只有一个消费者。

最新更新