【问题标题】:Detecting pipe hangup检测管道挂起
【发布时间】:2020-07-06 20:44:38
【问题描述】:

如何在读取器进程中知道管道的写入端是否仍处于活动状态(写入器进程没有关闭其描述符或退出)。我的意思是 Posix(C 语言)接口。看起来,如果读取器进程具有描述符 NONBLOCK,则无法通过“读取”调用的效果来猜测。我尝试检查描述符标志,但它们没有改变:

作者:

#include <unistd.h>

int main() {
    sleep(2);
    //actually doesn't write anything but has
    //stdout open and exits before reader does
}

读者:

#include <fcntl.h>
#include <cstdio>
#include <unistd.h>


int main() {
    
    int i = fcntl(0, F_GETFL);
    int j = fcntl(0, F_GETFD);
    //now the write end is alive
    printf("i: %d, j: %d\n", i, j);
    sleep(3);
    i = fcntl(0, F_GETFL);
    j = fcntl(0, F_GETFD);
    //now the write end has exited
    printf("i: %d, j: %d\n", i, j);
    //all flags are all the time 0
}

假设这些程序被某个外部程序连接到管道中(使用“管道”调用)。

【问题讨论】:

    标签: pipe posix


    【解决方案1】:

    read 将在管道的写入端关闭并读取所有待处理数据后返回 0。如果没有数据且管道未关闭且启用非阻塞模式read 将返回-1 并设置在errnoEAGAIN

    当写入端关闭时,poll 将为管道返回一个POLLHUP 事件。

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 2019-11-23
      • 2012-12-20
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多