gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:26:33 24 4
gpt4 key购买 nike

我面临在 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: %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);
}

最佳答案

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

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

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

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

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

关于C 中命名管道的消费者 - 生产者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com