Search code examples
pythonunixselectpipewaitpid

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


My python program creates a pipe, forks, and then spawns another program from the child. The parent then sits and waits for the reader-side of the pipe to become readable.

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

For some reason, when the spawn child exits, the parent continues to wait in the select... Indefinitely... How is one supposed to detect this situation?


Solution

  • There is a deadlock since parent process' writer is not closed before going to select. You could also close the writer in the parent process:

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