【发布时间】:2018-09-26 16:05:09
【问题描述】:
我的老师说如果管道的写端关闭,子进程就不能再从管道的读端读取,读取会产生BROKEN _PIPE错误。但是,在封闭管上阅读时,我无法让此代码产生任何错误:
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
int main(void) {
int pipefd[2];
char c;
pipe(pipefd);
if (fork() == 0) {
close(pipefd[1]);
sleep(5);
// The parent has already closed pipefd[1]
while (read(pipefd[0], &c, 1)) {
printf("%c", c);
}
close(pipefd[0]);
return 0;
}
close(pipefd[0]);
char str[] = "foo";
write(pipefd[1], str, 4);
close(pipefd[1]);
return 0;
}
5 秒后标准输出上的输出为foo。所以我的理解是,关闭写入端只是在已经存在的字符之后添加 EOF,并且不会在任何即将读取的内容中发送 EOF(因此孩子可以读取所有已经发送的字符)。我说的对吗?
【问题讨论】: