c - 消费者 - 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: %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);
}
解决方案
好的,我自己在这两种情况下都找到了解决方案,我将此块添加到生产者方法中:
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;
}
我以这种方式解决了我的问题,对于多个生产者 - 单个消费者,我们可以省略消费者循环,因为它在第一个代码片段中,因为只有一个消费者。
推荐阅读
- javascript - 在所有时区中使用 JavaScript 将 Excel 日期序列号转换为日期
- c - 如何从 32 位程序中获取 64 位“程序文件”文件夹路径
- android - kotlin androidpdfviewer lib 似乎没有加载
- optimization - 解决受条件约束限制的优化问题
- python - Python 3.8+,在 lambda 函数中赋值
- spring - 如何在 Spring Boot 中使用 JavaMail 发送邮件?
- java - 使用Java中的流将2个列表的项目相乘和相加
- azure-active-directory - Azure Active Directory 能否用于后端(NodeJS)的完整用户管理
- apache-flink - Apache Flink - 检查点/保存点如何工作如果我们运行重复作业(多租户)
- python - 将 CNN 连接到 RNN