当父进程退出时,如何让子进程处于活动状态?

时间:2014-07-11 09:42:40

标签: python multiprocessing

我想使用multiprocessing模块来完成此操作。

当我这样做时,比如:

    $ python my_process.py

我启动父进程,然后让父进程生成子进程

然后我希望父进程退出,但子进程继续工作。

请允许我写一个错误代码来解释自己:

from multiprocessing import Process

def f(x):
    with open('out.dat', 'w') as f:
        f.write(x)

if __name__ == '__main__':
    p = Process(target=f, args=('bbb',))
    p.daemon = True    # This is key, set the daemon, then parent exits itself
    p.start()

    #p.join()    # This is WRONG code, just want to exlain what I mean.
    # the child processes will be killed, when father exit

那么,如何在父进程完成时启动一个不会被杀死的进程?


20140714

大家好,你们

我的朋友告诉我一个解决方案......

我只是想......

无论如何,让你看看:

import os
os.system('python your_app.py&')    # SEE!? the & !!

这确实有用!!

2 个答案:

答案 0 :(得分:6)

技巧:调用os._exit使父进程退出,这样就不会杀死守护进程子进程。

但是还有一些其他的副作用,在doc中描述:

Exit the process with status n, without calling cleanup handlers, 
flushing stdio buffers, etc.

如果你不关心这个,你可以使用它。

答案 1 :(得分:0)

这是一种实现独立的子进程的方法,该子进程在__main__退出时不会退出。它使用@WKPlus上面提到的os._exit()技巧。

Is there a way to detach matplotlib plots so that the computation can continue?

相关问题