【发布时间】:2021-07-28 23:00:53
【问题描述】:
根据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;
}
【问题讨论】:
-
始终计算 fds。在
pipe之后,你有 2 个。在 fork 之后,你有 4 个。在 close 之后,你有 3 个。两个读,一个写。您需要关闭另一个写入端。