你如何在 C 中使用 children 从管道中读取数据?

How do you read from pipe with both children in C?

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

每当我尝试 运行 程序时,只有第二个 CHILD 可以从管道读取,第一个 CHILD 永远不会。所以我尝试评论第二个 child 的管道读数,但是第一个 child 仍然无法从 parent 写入的管道中读取。

为什么 1ST CHILD 不能从管道读取?

感谢您的帮助!

顺序有误。您的代码是

pid = fork();

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

您需要在分叉之前创建管道。如果您检查 close and/or 和 read.

上的错误,您可能会发现此类错误