Python Multiprocessing Continue Running Until Stop Signal (Kill Process)

November 18, 2020
import signal
import multiprocessing as mp
import os

stop_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 shutdown
signal.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
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.