父进程退出时如何让子进程存活?

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.

这篇关于父进程退出时如何让子进程存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)