0

I'm trying to:

  1. launch a background process (a python script)
  2. run some bash commands
  3. 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)
Isaac Turner
  • 2,673
  • 1
  • 26
  • 25

1 Answers1

0

The point is SIGINT is used to terminate foreground process. You should directly use kill $pid to terminate background process.

BTW, kill $pid is equal to kill -15 $pid or kill -SIGTERM $pid.

Update

You can use signal module to deal with this situation.

import signal
import sys
def handle(signum, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, handle)
print("Running")
while True:
    pass
Sraw
  • 18,892
  • 11
  • 54
  • 87
  • I want to send an interrupt (equivalent to pressing control-C) which I can catch in python to shutdown cleanly. `SIGTERM` just terminates the background process. – Isaac Turner Aug 22 '17 at 01:46
  • OK, I got your point, and I will update my answer. – Sraw Aug 22 '17 at 01:53