問題描述
我想使用 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模板網!