Manually (ctrl+c) cancelling
python child.py
Sleeping
.
.
.
.
^CReceived 2 , exiting 10
Cancelling from parent and subprocess.Popen.send_signal
$ python parent.py
Sleeping
.
.
Sending SIGINT to child
Received 2 , exiting 10
Child exited with 10
# will sleep 10 sec and exit with code 0, unless it receives SIGINT (ctrl+c), | |
# in that case it exits with code 10 | |
import signal, sys, time | |
def signal_handler(sig, frame): | |
print('Received', sig, ", exiting 10") | |
sys.exit(10) | |
signal.signal(signal.SIGINT, signal_handler) | |
print("Sleeping ") | |
for _ in range(10): | |
print(".") | |
time.sleep(1) | |
print("Didn't receive signal, exiting 0") | |
sys.exit(0) |
import signal, subprocess, sys, time | |
proc = subprocess.Popen([sys.executable, "child.py"]) | |
time.sleep(2) | |
print("Sending SIGINT to child") | |
proc.send_signal(signal.SIGINT) | |
proc.wait() | |
print("Child exited with", proc.returncode) |