Warm tip: This article is reproduced from serverfault.com, please click

linux-你如何从两个孩子都在C的管道中读取内容?

(linux - How do you read from pipe with both children in C?)

发布于 2020-12-03 16:40:14
int main()
{
    int pipefd[2];
    char buf;

    int pid, pid1;
    pid = fork();

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    if(pid == 0){                    // CHILD 1
        close(pipefd[1]);

        while(read(pipefd[0],&buf,1) > 0){                       // THIS DOESNT WORK
            printf("FIRST CHILD WRITES: %s\n",&buf);             // THIS DOESNT WORK
        }                                                        // THIS DOESNT WORK
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);

    }else{
        pid1 = fork();

        if(pid1 == 0){                     // CHILD 2
            close(pipefd[1]);

            // while(read(pipefd[0],&buf,1) > 0){                 // ONLY THIS (WOULD) WORK
            //     printf("SECOND CHILD WRITES: %s\n",&buf);      // ONLY THIS (WOULD) WORK
            // }                                                  // ONLY THIS (WOULD) WORK

            close(pipefd[0]);
            _exit(EXIT_SUCCESS);

        }else{                               // PARENT
            close(pipefd[0]);
            char* s = "Write To Pipe";
            write(pipefd[1],s,strlen(s));
            close(pipefd[1]);

            wait(NULL);            // WAIT FOR CHILD TO TERMINATE
            wait(NULL);            // WAIT FOR CHILD TO TERMINATE
        }
    }

    return 0;
}

每当我尝试运行该程序时,只能从管道读取第二个孩子,而第一个孩子则永远无法读取。因此,我尝试评论第二个孩子的管道读数,但是第一个孩子仍然无法从父级写入的管道中读取。

为什么不能从管道中读取第一个孩子?

谢谢你的帮助!

Questioner
PizzaPeet
Viewed
0
William Pursell 2020-12-04 00:50:26

顺序错误。你的代码是

pid = fork();

if (pipe(pipefd) == -1) {
    perror("pipe");
    exit(EXIT_FAILURE);
}

你需要先创建管道,然后再进行分叉。如果检查close和和或上的错误,则可能会捕获此类错误read