title: Bash: Waiting on a background python process
body: <p>I'm trying to:</p>
  
  <ol>
  <li>launch a background process (a python script)</li>
  <li>run some bash commands</li>
  <li>Then send control-C to shut down the background process once the foreground tasks are finished</li>
  </ol>
  
  <p>Minimal example of the what I've tried - Python <code>test.py</code>:</p>
  
  <pre><code>import sys
  
  try:
      print("Running")
      while True:
          pass
  except KeyboardInterrupt:
      print("Escape!")
  </code></pre>
  
  <p>Bash <code>test.sh</code>:</p>
  
  <pre><code>#!/bin/bash
  
  python3 ./test.py &amp;
  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
  </code></pre>
  
  <p>But the bash script seems to be hanging on the wait and the SIGINT signal is not being sent to the python process. </p>
  
  <p>I'm using Mac OS X, and am looking for a solution that works for bash on linux + mac. </p>
  
  <p><strong>Edit:</strong> 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:</p>
  
  <pre><code>import signal
  signal.signal(signal.SIGINT, signal.default_int_handler)
  </code></pre>