问题描述
我想使用multiprocessing
模块来完成此操作.
I want to use multiprocessing
module to complete this.
当我这样做时,例如:
$ python my_process.py
我启动一个父进程,然后让父进程产生一个子进程,
I start a parent process, and then let the parent process spawn a child process,
然后我希望父进程退出自身,但子进程继续工作.
then i want that the parent process exits itself, but the child process continues to work.
允许我写一个 WRONG 代码来说明自己:
Allow me write a WRONG code to explain myself:
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
那么,我如何启动一个在父进程完成时不会被杀死的进程?
So, how do i start a process that will not be killed when the parent process finishes?
20140714
大家
我的朋友刚刚告诉我一个解决方案...
My friend just told me a solution...
我只是想...
无论如何,让你看看:
import os
os.system('python your_app.py&') # SEE!? the & !!
这确实有效!
推荐答案
一个技巧:调用os._exit
退出父进程,这样就不会杀死守护进程.
A trick: call os._exit
to make parent process exit, in this way daemonic child processes will not be killed.
但是还有其他一些副作用,请参见文档:
But there are some other side affects, described in the doc:
Exit the process with status n, without calling cleanup handlers,
flushing stdio buffers, etc.
如果您对此不关心,可以使用它.
If you do not care about this, you can use it.
这篇关于当父进程退出时,如何让子进程存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!