首页 > 解决方案 > 消费者 - 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);
}

标签: cunixpipeipcproducer-consumer

解决方案


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

 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;
        }

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


推荐阅读