1

I have some code like this

import multiprocessing as mp

processes = []
for i in range(10):
  p = mp.Process(target=my_func, args=args)
  processes.append(p)
  p.start()

for p in processes:
  p.join()

If there is a bug in my_func that causes all the threads to crash, then I want my parent process to detect that and also throw an exception. How can I detect if the process exited cleanly when I join the processes?

Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
Aaron
  • 2,354
  • 1
  • 17
  • 25
  • What exception you get? – Yeheshuah Mar 05 '20 at 05:08
  • Doesn't matter what exception I get. I keep making bugs in the my_func function and it causes the threads to exit and the program to continue. What I want is for if the threads exit with an exception that then the master process can detect it and exit as well. – Aaron Mar 05 '20 at 05:10
  • 2
    Does this answer your question? [Python Multiprocessing: Handling Child Errors in Parent](https://stackoverflow.com/questions/19924104/python-multiprocessing-handling-child-errors-in-parent) – felipe Mar 05 '20 at 05:20

2 Answers2

1

read the value of the process' exitcode:

  • None if the process has not finished yet.
  • 0 if the process ended successfully.
  • N if the process had an error, and exited with code N.
  • -N if the process was killed with the signal N. (eg. -15 if killed by SIGTERM)

For example, in your main process:

for p in processes:
    p.join()
    if p.exitcode > 0:
        raise ValueError(f'a process exited with code {p.exitcode}')

And in your runnable:

try:
    do_something()
except KnownError as _:
    exit(my_known_error_code)
fixmycode
  • 8,220
  • 2
  • 28
  • 43
1

You can check exit code after calling join().

For example:

for p in processes:
  p.join()
  if p.exitcode is not 0:
    exit(1)

Reference:

Yeheshuah
  • 1,216
  • 1
  • 13
  • 28