【问题标题】:Reading a widowed pipe hangs读守寡的管道挂起
【发布时间】: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 个。两个读,一个写。您需要关闭另一个写入端。

标签: c pipe


【解决方案1】:

在管道真正关闭之前,我需要在父进程中关闭管道的写端。

【讨论】:

  • 在fork 之后,您应该立即关闭两个进程中未使用的管道末端(或者在duping 之后,如果这是用例)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多