我的老师说,如果管道的写入端关闭,子进程将无法再从管道的读取端读取,读取会产生 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 秒后 stdout 上的输出是 foo
。所以我的理解是,关闭写端只是在已经存在的字符之后添加 EOF,并且不会在任何即将到来的读取中发送 EOF(这样 child 就可以读取所有已经发送的字符)。我说得对吗?
最佳答案
正如你所发现的,你的老师错了。
当您尝试从破损的管道读取,但是当您尝试写入到破损的管道时。关于c - 即使写端关闭也从管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522006/