我想使用 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.
请允许我写一个错误代码来解释我自己:
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.
但是还有一些其他的副作用,在 doc一个>:
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.
这篇关于父进程退出时如何让子进程存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!