在Python3.4中的fork进程中从管道读取时出现“Bad file descriptor”错误。

3

我使用Python3.4的os.pipe来实现父子进程间的进程间通信,通过os.execlp args传递管道参数。

  self.child_pipe_read=int(sys.argv[2])
  self.child_pipe_write=int(sys.argv[3])

...

  os.execlp('python3','python3','child_test.py',str(pid),str(self.child_pipe_read) ,str(self.child_pipe_write))

然而,当我使用这个时:
msg=os.read(self.child_pipe_read,32)

抛出错误 OSError: [Errno 9] 坏的文件描述符

然后我尝试向管道写入:

 os.write(self.parent_pipe_write,(msg+'\n').encode())

BrokenPipeError: [Errno 32] Broken pipe

翻译:管道破裂错误:[Errno 32] 管道破裂

我看到了Python3.4的文档,发现这个内容:

"从3.4版本开始更改:新的文件描述符现在是不可继承的",但我不知道它的含义是什么?如何使用管道进行进程间通信?

翻译: "从3.4版本开始更改:新的文件描述符现在是不可继承的",但我不知道它的含义是什么?如何使用管道进行进程间通信?


你的代码甚至没有显示管道的创建。请添加它。此外,查看如何创建一个最小化、可验证的示例,以获取有用答案的提示。 - spectras
1个回答

1

默认情况下允许继承文件描述符被认为是一种安全漏洞,因此在 Python 3.4 中进行了更改。您必须通过调用 os.set_inheritable(fd, True) 显式标记文件描述符为可继承的。请注意,此函数是 Python 3.4 中的新功能。


self.child_pipe_read,self.parent_pipe_write=os.pipe() self.parent_pipe_read,self.child_pipe_write=os.pipe() os.set_inheritable(self.child_pipe_read, True) os.set_inheritable(self.child_pipe_write, True) os.set_inheritable(self.parent_pipe_read, True) os.set_inheritable(self.parent_pipe_write, True) - minghu6
我甚至尝试了以下方法,但在我的子进程中仍然抛出 OSError 坏文件描述符。 - minghu6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接