Python3 中 os.execvp() 有任何 file-descriptor 变化吗?

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

我有一个脚本,它在 Python-2 下运行良好。它使用 os.pipe() 创建管道,然后将管道写入端的描述符传递给 child 进程:

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

在 Python-2 下,上述工作正常,child 写入指定的 file-descriptor -- 允许 parent 读取它。

在 Python-3 下,child 抱怨无法打开 /dev/fd/4——这意味着,描述符没有传递给某些 child原因。那是什么原因 - 是否可以用旧的预期行为调用 os.execvp

这不是对 os.execvp 的更改,而是对 os.pipe 的更改。请注意 the Python 3 documentation says "The new file descriptor is non-inheritable", but the Python 2 documentation 不会。如 link 中所述,要使其在 Python 3 中工作,请执行 os.set_inheritable(writer, True)。 (顺便说一句,这意味着您的 os.close(reader) 是多余的,因为它也不可继承,因此您可以删除该行。)