你能解释一下为什么即使父进程关闭了它的写入端,子进程仍然可以读取吗?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd[2];
char buffer[20];
pipe(fd);
if ( fork() == 0 ) //child
{
close(fd[0]); //As it is writing close the read end
strcpy(buffer, "Hello World");
write(fd[1], buffer, sizeof(buffer));
close(fd[1]);
}
else //parent
{
close(fd[1]); //As it is reading closing the write end
while(1)
{
read(fd[0], buffer, sizeof(buffer));
printf("Buffer:%s\n", buffer);
sleep(1);
}
close(fd[0]);
}
}
O/P: child 不断打印:
Buffer:Hello World
为什么即使 parent 终止, child 也能收到? read
不应该得到 EOF
吗?
最佳答案
Why is the child able to receive even when the parent terminates? Shouldn't
read
getEOF
?
此时父进程基本上没有读取任何内容(即:read()
正在返回 0
)并一遍又一遍地打印它在上一次调用中读取的内容到 read()
。
您必须查看 read()
系统调用返回的值。该值是 int
类型,基本上:
-1
:错误,出错了。0
:没有其他内容可读,即:EOF
(您要查找的内容)。- 否则:
read()
读取的 字节数 存储到buffer
中。
您可以相应地重写父级的 while
循环:
while(1) {
int count = read(fd[0], buffer, sizeof(buffer));
switch (count) {
case 0: // EOF
break;
case -1: // read() error
// ... error handling ...
break;
default: // fine
// count contains the number of bytes read
buffer[count] = '\0'; // NUL character, to indicate the end of string
printf("Buffer:%s\n", buffer);
sleep(1);
}
}
关于c - 即使在写端关闭后也从管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717635/