我想使用 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
大家好
我的 friend 刚刚告诉我一个解决方案...
我只是觉得...
不管怎样,让你看看:
import os
os.system('python your_app.py&') # SEE!? the & !!
这确实有效!!
最佳答案
技巧:调用os._exit
让父进程退出,这样daemonic子进程就不会被杀死。
但是还有一些其他的副作用,在 doc 中有描述。 :
Exit the process with status n, without calling cleanup handlers,
flushing stdio buffers, etc.
如果你不关心这个,你可以使用它。
关于python - 父进程退出时如何让子进程存活?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24694763/