From b2899aeb4455719fe622abeb250ab5f5d8b3a739 Mon Sep 17 00:00:00 2001 From: Adam Olech Date: Wed, 7 Apr 2021 13:00:38 +0200 Subject: Add signals_with_multiprocessing.py --- signals_with_multiprocessing.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 signals_with_multiprocessing.py diff --git a/signals_with_multiprocessing.py b/signals_with_multiprocessing.py new file mode 100644 index 0000000..4cf0c01 --- /dev/null +++ b/signals_with_multiprocessing.py @@ -0,0 +1,34 @@ +import multiprocessing, time, sys, signal, os, inspect + +# Sending SIGTERM will terminate the main process +# but the process running the 'a' function will remain dangling. + +def signal_handler(sig, fr): + print(inspect.stack()[0][3]) + print('{}: Received {}'.format(os.getpid(), sig)) + sys.exit(3) + # the statement below never executes, leaving the process dangling. + # p.terminate() + +signal.signal(signal.SIGTERM, signal_handler) + +def a(b): + def signal_handler(sig, fr): + print(inspect.stack()[0][3]) + print('{}: 2Received {}'.format(os.getpid(), sig)) + sys.exit(5) + + # The process normally inherits parent signal handler + # but we overwrite it here. + signal.signal(signal.SIGTERM, signal_handler) + + while True: + print('{}: {}'.format(os.getpid(), b)) + time.sleep(1) + +p = multiprocessing.Process(target=a, args=('cool test',)) +p.start() + +print('PID: {}'.format(os.getpid())) + +sys.exit(4) -- cgit v1.2.1