阅读寡妇管道挂起

问题描述

根据pipe (2)

读或写结束的管道被认为是寡妇的。 在这样的管道上写入会导致写入进程收到一个 SIGPIPE 信号。隐藏管道是将文件结尾传送到 阅读器:在阅读器消耗任何缓冲数据后,读取一个寡妇 管道返回零计数。

我的理解是,从关闭的管道读取应该导致读取器返回读取的 0 个字节。但是,在下面的测试程序中,read 调用阻塞,程序挂起。我觉得我好像在 man 页面上遗漏了一些东西;为什么这个程序会阻塞?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void child(int pipe) {
        close(pipe);
}

void parent(int pipe) {
        char b;
        ssize_t nread;

        printf("about to read\n");

        nread = read(pipe,&b,1);

        printf("nread = %zd\n",nread);
}

int main(void) {
        pid_t pid;
        int pipes[2];

        pipe(pipes);

        pid = fork();

        if (pid == 0)
                child(pipes[1]);
        else
                parent(pipes[0]);

        return 0;
}

解决方法

我需要在管道真正关闭之前关闭父进程中管道的写端。