1
#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")

An exception is raised in the main-process, but child- and main-process keep running. Why?

Darkonaut
  • 20,186
  • 7
  • 54
  • 65
  • see https://stackoverflow.com/questions/23716951/python-multiprocessing-how-to-exit-cleanly-after-an-error – Melvin Jun 11 '19 at 02:25
  • @Melvin actually, I know what to do to make the child process exit. I just want to know what happened when there's no daemon flag or excepthook – hustxujinkang Jun 11 '19 at 02:29

1 Answers1

1

When the MainProcess is shutting down, non-daemonic child processes are simply joined. This happens in _exit_function() which is registered with atexit.register(_exit_function). You can look it up in multiprocessing.util.py if you are curious.

You can also insert multiprocessing.log_to_stderr(logging.DEBUG) before you start your process to see the log messages:

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
Darkonaut
  • 20,186
  • 7
  • 54
  • 65