title: Python: Ignoring signals in background process
body: <p>I am creating a Python program that calls an external command periodically. The external command takes a few
  seconds to complete. I want to reduce the possibility of the external command terminating
  badly by adding a signal handler for SIGINT. Basically,  I want SIGINT to attempt to wait until the command
  executes before terminating the Python program. The problem is that the external perogram seems to be
  getting the SIGINT as well, causing it to end abruptly. I am invoking the command using an external thread, since
  the Python documentation for signal mentions that only the main thread receives the signal, according to <a href="http://docs.python.org/2/library/signal.html" rel="nofollow">http://docs.python.org/2/library/signal.html</a>.
  Can someone help with this.
  Here is a stub of my code. Imagine that the external program is /bin/sleep:</p>
  
  <pre><code>import sys
  import time
  import threading
  import signal
  def sleep():
    import subprocess
    global sleeping
    cmd = ['/bin/sleep', '10000']
    sleeping  = True
    p = subprocess.Popen(cmd)
    p.wait()
    sleeping = False
  
  def sigint_handler(signum, frame):
    if sleeping:
       print 'busy, will terminate shortly'
       while(sleeping): time.sleep(0.5)
       sys.exit(0)
    else:
       print 'clean exit'
       sys.exit(0)
  
  sleeping = False
  signal.signal(signal.SIGINT, sigint_handler)
  while(1):
    t1 = threading.Thread(target=sleep)
    t1.start()
    time.sleep(500)
  </code></pre>
  
  <p>The expected behavior is that pressing Ctrl+C N seconds after the program starts will result in 
  it waiting (10000 - N) seconds and then exiting. What is happening is the program immediately terminates.</p>
  
  <p>Thanks!</p>