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



我的python程序创建一个管道,分叉,然后从子程序生成另一个程序。然后,父级坐下来等待管道的读取器端变得可读。

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], [], [])
.....

出于某种原因,当生成子项退出时,父项继续在select中等待......无限期。。。应该如何发现这种情况?

由于父进程的编写器在进行选择之前未关闭,因此存在死锁。您还可以在父进程中关闭编写器:

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

最新更新