- Use multiprocessing.Event as the stop signal for child process.
- Integrate Event.wait() as part of child process loop
- Use signal.SIGTERM to listen to external stop command
import signalimport multiprocessing as mpimport osstop_event = mp.Event()def run(name, stop_event): while not stop_event.wait(0.5): print(f"{name}", end='', flush=True) print(f"{name}[END]", end='', flush=True)def stop(signum, frame): global stop_event print(f"SIG[{signum}]") stop_event.set()# os shutdownsignal.signal(signal.SIGTERM, stop)# ctrl-c# signal.signal(signal.SIGINT, stop)print(f"PID[{os.getpid()}]")jobs = []for name in ['a', 'b', 'c']: p = mp.Process(target=run, args=(name, stop_event)) p.start() jobs.append(p)for p in jobs: p.join()print(f"STOP")
PID[94774]
bcacbacbacbacbacbacbacbacbacbacbacbacbacbabacbacbacbacbcabcabcaSIG[15]
a[END]c[END]b[END]STOP
Stop the application using
kill 94774