基本管道不终止于 c

Basic pipe does not terminate in c

我尝试运行下面的简单代码:

int main(int argc, char* argv[]) {
    int fds[2];
    pipe(fds);
    int pid1, pid2;
    if ((pid1 = fork()) == 0){
        close(fds[0]); // close read end
        dup2(fds[1], 1); // connect write end
        char *argv1[2] = {"echo", "hi"};
        execvp(argv1[0], argv1);
    }
    if ((pid2 = fork()) == 0){
        close(fds[1]); // close write end
        dup2(fds[0], 0); // connect read end
        char *argv2[2] = {"wc", "-c"};
        execvp(argv2[0], argv2);
    } 
    int status;
    waitpid(pid1, &status, 0);
    printf("pid=%d terminated with status=%d\n", pid1, status);
    waitpid(pid2, &status, 0);
    printf("pid=%d terminated with status=%d\n", pid2, status);
    return 0;
}

我原以为 echowc 都会终止,但 wc 从来没有。 我从上面的代码得到的输出如下所示(主进程暂停等待 wc 完成)。

pid=2802 terminated with status=0

Any ideas why the second forked process doesn't finish?


我已经检查过,通过在主进程短暂 sleep 后尝试从 fds[0] 读取,wc 命令确实读取了 hi 消息来自回声。

您需要关闭管道的所有写入端。该文件描述符有 4 个副本,并且 wc 在所有副本都关闭之前不会终止。 echo 将在终止时关闭其两个副本,但最好在执行之前明确关闭未使用的副本:

dup2(fds[1], STDOUT_FILENO);
close(fds[1]);

在调用 waitpid

之前,您还需要在父级中关闭该文件描述符