How to let the child process live when parent process exited?(父进程退出时如何让子进程存活?)
问题描述
我想使用 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.
这篇关于父进程退出时如何让子进程存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:父进程退出时如何让子进程存活?
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01