分离使用Python multiprocessing模块启动的子进程

10 投票
1 回答
6617 浏览
提问于 2025-04-15 16:08

我想用Python的multiprocessing模块创建一个进程,但希望在创建这个子进程的主进程退出后,子进程还能继续运行。

我可以用subprocess模块和Popen来实现这个功能,但我想把我的代码写成一个函数,而不是一个脚本。我这样做的原因是为了简化创建pyro(Python远程对象)对象的过程。我想用multiprocessing在一个单独的进程中启动pyro对象的请求处理器,但同时我希望主进程可以退出,而支持pyro对象的那个进程继续运行。

1 个回答

4

我终于得到了我想要的东西。感谢任何能帮助我改进代码的建议。

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()

撰写回答