Detect Process Failure and Reclaim Resources
Core idea
Process.join waits for termination, not successful work. Inspect exitcode: zero normally means success, nonzero means failure, and negative values on POSIX indicate a signal. Prefer cooperative stopping and resource cleanup; terminate is a last resort because it can interrupt finally blocks, damage queues or leave locks held. Close process handles after termination. Run process examples as scripts.
from multiprocessing import get_contextdef worker(): raise SystemExit(3)if __name__ == '__main__': p = get_context('spawn').Process(target=worker) p.start() p.join() print(p.exitcode, p.is_alive()) p.close()The worker ended but its explicit exit status is nonzero.
Expected output:
3 FalseSignal cooperative completion
from multiprocessing import get_contextdef worker(stop, ready): ready.set() stop.wait()if __name__ == '__main__': ctx = get_context('spawn') stop, ready = ctx.Event(), ctx.Event() p = ctx.Process(target=worker, args=(stop, ready)) p.start() try: if not ready.wait(5): raise TimeoutError('worker not ready') finally: stop.set() p.join() print(p.exitcode) p.close()The parent signals the worker rather than killing it, then observes its exit status.
Expected output:
0Common mistake
After join(timeout), check is_alive before closing the Process. In real supervision add a bounded escalation policy and account for outstanding work; terminate does not reliably clean descendants or shared resources.
Practice
Design a supervisor that reports a nonzero exit status, requests cooperative stop and uses a documented escalation policy if the worker remains alive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Process failure and cleanup
Check your understanding of process failure and cleanup.
What is printed?
from multiprocessing import get_contextp=get_context("spawn").Process(target=print)print(p.exitcode is None)p.close()What is printed?
def successful(code): return code == 0print(successful(3),successful(0))Does join alone establish successful work?
Why avoid abrupt termination when possible?