Any file-descriptor changes in os.execvp() in Python3?

Viewed 164

I have a script, which works reasonably well under Python-2. It uses os.pipe() to create a pipe, and then passes the descriptor of the writing side of the pipe to a child process:

    reader, writer = os.pipe()
    pid = os.fork()
    if pid == 0:
        # Child
        os.close(reader)
        os.execvp('command', ['command', '-o', '/dev/fd/%d' % writer])
    ...

Under Python-2 the above works, and the child writes to the specified file-descriptor -- allowing the parent to read it.

Under Python-3 the child complains about being unable to open the /dev/fd/4 -- which means, the descriptor is not passed to the child for some reason. What would that reason be -- and is it possible to invoke os.execvp with the old, expected, behavior?

1 Answers

It's not a change to os.execvp but rather a change to os.pipe. Note that the Python 3 documentation says "The new file descriptor is non-inheritable", but the Python 2 documentation does not. As explained in that link, to make it work in Python 3, do os.set_inheritable(writer, True). (And by the way, this means that your os.close(reader) is redundant, since it's not inheritable either, so you can remove that line.)

Related