【问题标题】:Detach a subprocess started using python multiprocessing module分离使用 python 多处理模块启动的子进程
【发布时间】:2010-12-17 23:04:47
【问题描述】:
我想在 python 中使用 mutliprocessing 模块创建一个进程,但确保它在创建子进程的进程退出后继续运行。
我可以使用 subprocess 模块和 Popen 获得所需的功能,但我想将我的代码作为函数而不是脚本运行。我想这样做的原因是为了简化创建 pyro(python 远程对象)对象。我想使用多处理在单独的进程中启动 pyro 对象请求处理程序,但随后我希望主进程退出,同时支持 pyro 对象的进程继续运行。
【问题讨论】:
标签:
python
subprocess
multiprocessing
detach
pyro
【解决方案1】:
我终于得到了我想要的。我感谢任何改进代码的建议。
def start_server():
pyrodaemon = Pyro.core.Daemon()
#setup daemon and nameserver
#Don't want to close the pyro socket
#Need to remove SIGTERM map so Processing doesn't kill the subprocess
#Need to explicitly detach for some reason I don't understand
with daemon.DaemonContext(files_preserve=[pyrodaemon.sock],signal_map={signal.SIGTERM:None},detach_process=True):
while running:
pyrodaemon.handleRequests(timeout=1.0)
#when finished, clean up
pyrodaemon.shutdown()
def main():
p = Process(target=start_server)
p.daemon=True # Need to inform Process that this should run as a daemon
p.start()
time.sleep(3.0) # Important when running this program stand alone: Must wait long enough for start_server to get into the daemon context before the main program exits or Process will take down the subprocess before it detaches
do_other_stuff_not_in_the_daemon()
【讨论】:
-
daemon 这个词在这里被滥用了 ;) 不要 将 Process.daemon 设置为 True。这告诉多处理尝试在退出时杀死孩子(令人困惑吧?)。我认为这就是为什么您需要在上面的代码中捕获 SIGTERM 并设置 detach_process 的原因。 - docs.python.org/library/…