分离使用python multiprocessing模块启动的子进程 [英] Detach a subprocess started using python multiprocessing module

查看:312
本文介绍了分离使用python multiprocessing模块启动的子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a process using the mutliprocessing module in python but ensure it continues running after the process that created the subprocess exits.

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

I can get the required functionality using the subprocess module and Popen, but I want to run my code as a function, not as a script. The reason I want to do this is to simplify creating pyro (python remote objects) objects. I want to start the pyro object request handler in a separate process using multiprocessing, but then I want the main process to exit while the process supporting the pyro object continues to run.

推荐答案

我终于得到了想要的东西.感谢您提出的改进代码的建议.

I finally got what I wanted. I appreciate any suggestions to improve the code.

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

这篇关于分离使用python multiprocessing模块启动的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆