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

kkk*_*kv_ 8 python multiprocessing

我想用multiprocessing模块来完成这个.

当我这样做时,像:

    $ python my_process.py
Run Code Online (Sandbox Code Playgroud)

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

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


20140714

嗨,你们

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

我只是想...

无论如何,只是让你看看:

import os
os.system('python your_app.py&')    # SEE!? the & !!
Run Code Online (Sandbox Code Playgroud)

这确实有效!!

WKP*_*lus 7

一招:调用os._exit父进程退出,这样就不会杀死守护进程子进程.

但是在文档中描述了一些其他的副作用:

Exit the process with status n, without calling cleanup handlers, 
flushing stdio buffers, etc.
Run Code Online (Sandbox Code Playgroud)

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