消费者-C

时间:2018-10-27 15:01:13

标签: c unix pipe ipc producer-consumer

我很难在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);
}

1 个答案:

答案 0 :(得分: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;
        }

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