分离使用python多处理模块启动的子进程

时间:2009-11-18 16:48:38

标签: python subprocess multiprocessing detach pyro

我想在python中使用mutliprocessing模块创建一个进程,但确保在创建子进程的进程退出后继续运行。

我可以使用子进程模块和Popen获得所需的功能,但我想将我的代码作为函数运行,而不是作为脚本运行。我想这样做的原因是简化创建pyro(python远程对象)对象。我想在使用多处理的单独进程中启动pyro对象请求处理程序,但是我希望在支持pyro对象的进程继续运行时退出主进程。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您要做的是启动一个守护进程。 查看PEP-3143python-daemon包。

看看Pyro,似乎它们包含了自己的守护模块,

Pyro/ext/daemonizer.py