gpt4 book ai didi

python - 即使子进程不存在,MultiProcessing Pipe recv 也会阻塞

转载 作者:太空狗 更新时间:2023-10-30 01:02:00 26 4
gpt4 key购买 nike

阅读关于这个主题的几个问题,我现在明白子进程从父进程继承文件描述符。这将使 child 在 parent 关闭连接时更难收到 EOFError。

但我的情况正好相反,我不明白我面临的问题。

我有一个启动子进程的父进程,并允许它访问我创建的管道连接的一端。现在,当子进程完成、出现故障或其他任何情况时,一切都会停止并且连接会关闭。此时子进程显示已失效。

然后我希望父进程的连接在阻塞的 recv 调用上抛出 EOFError。但它只是坐在那里等待。

我在这里错过了什么?

编辑

我认为这个例子代表了问题:

from multiprocessing import Process, Pipe
from threading import Thread
import time

class Parent(object):

def __init__(self):
self.parent_conn, child_conn = Pipe()
self.child = Process(target=Child, args=(child_conn,))
self.child.start()

def recv():
try:
self.parent_conn.recv()
except EOFError:
print "EOF"
except:
print "something else"

# Does not work
recv()

# Works fine
t = Thread(target=recv)
t.setDaemon(True)
t.start()

def close(self):
self.parent_conn.close()
self.child.join()

class Child(object):

def __init__(self, conn):
conn.close()

if __name__ == "__main__":
p = Parent()
time.sleep(1)
p.close()

如果我确实使用单独的线程,则允许父线程关闭自己的连接并且一切正常。 (请注意,您仍然需要以某种方式知道 child 已经完成,才能执行此操作)相反,如果我直接调用 recv,它显然会阻塞,但我怀疑它会在子进程关闭连接后立即引发 EOFError。但事实并非如此。谁能解释一下?

最佳答案

self.child.start() 之后添加 child_conn.close()。是idiomatic for working with pipes to close unused ends .还(可选)提供 duplex=False 参数。

The things is, I don't know beforehand whether it is going to close right away.. Normally the child should be able to send and receive. Furthermore I still do not get why this won't work, as is.

  1. child_conn.close()parent 中并不意味着 child 应该立即关闭它的结尾
  2. parent_conn.recv 只要有人有机会 child_conn.send() 就不会返回。如果 child_conn 被打开(在 child 或 parent 中)那么一个机会

If I do use the separate thread, the parent is allowed to close its own connection and everything works fine. Note that you still need to know somehow that the child is done for, to do this

你不需要知道它。您可以在 child 打开连接后立即关闭。在 self.child.start() 之后在父级中调用 child_conn.close() 是可以的,无论子级做什么。

Could you explain the duplex option a little bit more also?

duplex=False表示管道是单向的,即您只能调用 parent_conn.recv()child_conn.send()。否则它是双向的,并且两个连接都支持发送/接收。

关于python - 即使子进程不存在,MultiProcessing Pipe recv 也会阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com