#!/usr/bin/env python3 import signal import subprocess import sys def printef(*objects): print(*objects, file=sys.stderr, flush=True) def handler(signum, frame): signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN) if signum == signal.SIGINT: printef('raising KeyboardInterrupt') raise KeyboardInterrupt else: printef('raising SystemExit') sys.exit(1) def subproc(): printef('subproc:', sys.version_info) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) try: print('ready', flush=True) input() except KeyboardInterrupt: printef('handling KeyboardInterrupt') except SystemExit: printef('handling SystemExit') except: printef('handling something else:', sys.exc_info()) finally: printef('doing finally') def main(): proc = subprocess.Popen( [sys.executable, __file__, 'subproc'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # readline() to ensure that the signal handlers are already set ready = proc.stdout.readline().decode().strip() assert ready == 'ready' proc.send_signal(signal.SIGINT) proc.send_signal(signal.SIGTERM) rc = proc.wait() print('rc:', rc) sys.exit(rc) if __name__ == '__main__': if 'subproc' in sys.argv: subproc() else: main()