I'm trying to:
- launch a background process (a python script)
- run some bash commands
- Then send control-C to shut down the background process once the foreground tasks are finished
Minimal example of the what I've tried - Python test.py
:
import sys
try:
print("Running")
while True:
pass
except KeyboardInterrupt:
print("Escape!")
Bash test.sh
:
#!/bin/bash
python3 ./test.py &
pid=$!
# ... do something here ...
sleep 2
# Send an interrupt to the background process
# and wait for it to finish cleanly
echo "Shutdown"
kill -SIGINT $pid
wait
result=$?
echo $result
exit $result
But the bash script seems to be hanging on the wait and the SIGINT signal is not being sent to the python process.
I'm using Mac OS X, and am looking for a solution that works for bash on linux + mac.
Edit: Bash was sending interrupts but Python was not capturing them when being run as a background job. Fixed by adding the following to the Python script:
import signal
signal.signal(signal.SIGINT, signal.default_int_handler)