在 select() 中等待匿名管道变得可读时如何检测 child 的退出?

How to detect the child's exit when waiting in select() for the anonymous pipe to become readable?

我的 python 程序创建了一个管道、分支,然后从 child 生成了另一个程序。 parent 然后等待管道的 reader-side 变得可读。

    reader, writer = os.pipe()
    fcntl.fcntl(reader, fcntl.F_SETFL, os.O_NONBLOCK)
    child = os.fork()
    if child == 0:
        os.close(reader)
        os.execvp('program', ['program', '-o', '/dev/fd/%d' % writer])

    while True:
        if os.waitpid(child, os.WNOHANG) != (0, 0):
            break
        logger.debug('Going into select')
        r, w, x = select.select([reader], [], [])
        .....

出于某种原因,当 spawn child 退出时,parent 继续在 select 中等待...无限期...应该如何检测这种情况?

由于父进程的编写器在转到 select 之前未关闭,因此出现死锁。您也可以在父进程中关闭编写器:

if child == 0:
    os.close(reader)
    ...
else:
    os.close(writer)