为什么main和child进程在main中发生异常后不退出?

时间:2019-06-11 01:48:16

标签: python exception multiprocessing python-multiprocessing

#coding=utf8
from multiprocessing import Process
from time import sleep
import os 

def foo():
    print("foo")
    for i in range(11000):
        sleep(1)
        print("{}: {}".format(os.getpid(), i))


if __name__ == "__main__":
    p = Process(target=foo)
    #p.daemon = True
    p.start()
    print("parent: {}".format(os.getpid()))
    sleep(20)
    raise Exception("invalid")

在主进程中引发异常,但是子进程和主进程继续运行。为什么?

1 个答案:

答案 0 :(得分:1)

当MainProcess关闭时,将简单地加入非守护进程子进程。这发生在_exit_function()中注册的atexit.register(_exit_function)中。如果您感到好奇,可以在multiprocessing.util.py中查找它。

您也可以在开始查看日志消息之前插入multiprocessing.log_to_stderr(logging.DEBUG)

parent: 9670
foo
[INFO/Process-1] child process calling self.run()
9675: 0
9675: 1
...
9675: 18
Traceback (most recent call last):
  File "/home/...", line 26, in <module>
    raise Exception("invalid")
Exception: invalid
[INFO/MainProcess] process shutting down
[DEBUG/MainProcess] running all "atexit" finalizers with priority >= 0
[INFO/MainProcess] calling join() for process Process-1
9675: 19