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

标签 python multiprocessing

我想使用 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/

相关文章:

python - 只保留某一天 python 的最后一个时间戳

Python,从一行中提取所有表达式的问题(仅提取第一个)

python - 在 Python 中映射

python - Postgres : unterminated quoted string at or near using psycopg2

python - 使用多处理模块时无法将 Pandas 数据框对象发送到 SQL

python - 使用多个进程在 Python 中写入文件

python - 使用 Queue() 在 python 分布式应用程序中共享文件

python - 使用 python-pandas 索引数据帧时无法获得非唯一标签的正确切片绑定(bind)

python - 多处理:每个任务的进度条

c - 将子线程拆分为新的子线程 (Openmp)