检测管道挂起
Detecting pipe hangup
我如何才能知道,在 reader 进程中,管道的写入端是否仍然处于活动状态(写入进程没有关闭其描述符或退出)。我的意思是Posix(C语言)接口。看起来,如果 reader 进程具有描述符 NONBLOCK,则无法通过“read”调用的效果来猜测它。我尝试检查 desciptor 标志,但它们没有改变:
作者:
#include <unistd.h>
int main() {
sleep(2);
//actually doesn't write anything but has
//stdout open and exits before reader does
}
Reader:
#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
}
假设这些程序被一些外部程序连接到管道中(使用“管道”调用)。
read
将 return 0 一旦管道的写端关闭并且所有未决数据被读取。如果没有数据并且管道没有关闭并且启用了非阻塞模式 read
将 return -1 并在 errno
中设置为 EAGAIN
.
当写入端关闭时 poll
将 return 管道的 POLLHUP
事件。
我如何才能知道,在 reader 进程中,管道的写入端是否仍然处于活动状态(写入进程没有关闭其描述符或退出)。我的意思是Posix(C语言)接口。看起来,如果 reader 进程具有描述符 NONBLOCK,则无法通过“read”调用的效果来猜测它。我尝试检查 desciptor 标志,但它们没有改变:
作者:
#include <unistd.h>
int main() {
sleep(2);
//actually doesn't write anything but has
//stdout open and exits before reader does
}
Reader:
#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
}
假设这些程序被一些外部程序连接到管道中(使用“管道”调用)。
read
将 return 0 一旦管道的写端关闭并且所有未决数据被读取。如果没有数据并且管道没有关闭并且启用了非阻塞模式 read
将 return -1 并在 errno
中设置为 EAGAIN
.
当写入端关闭时 poll
将 return 管道的 POLLHUP
事件。