c - 即使在写端关闭后也从管道读取

标签 c linux operating-system pipe fork

你能解释一下为什么即使父进程关闭了它的写入端,子进程仍然可以读取吗?

#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 get EOF?

此时父进程基本上没有读取任何内容(即: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/

相关文章:

linux - 使用 CSV 文件中的换行符重新格式化项目

c - xv6 中的 PGROUNDUP 和 PGROUNDDOWN 是什么意思?

c - C 中变量的位置

c++ - syscalls.h 以及 minor() 和 major() 函数

c - 被跳过的指令是否有我没有看到的东西?

C - 如何将结构保存到内存的 malloc 部分?

c - 外部变量内存位置和编译/运行时行为

使用子进程时 Popen 出现 python 错误

python - 通过 subprocess.Popen() 调用时猫阻塞

linux - Signals在Linux和Windows下的实现?