title: Signal handling in multi-threaded Python
body: <p>This should be very simple and I'm very surprised that I haven't been able to find this questions answered already on stackoverflow.</p>
  
  <p>I have a daemon like program that needs to respond to the SIGTERM and SIGINT signals in order to work well with upstart. I read that the best way to do this is to run the main loop of the program in a separate thread from the main thread and let the main thread handle the signals. Then when a signal is received the signal handler should tell the main loop to exit by setting a sentinel flag that is routinely being checked in the main loop.</p>
  
  <p>I've tried doing this but it is not working the way I expected. See the code below:</p>
  
  <pre><code>from threading import Thread
  import signal
  import time
  import sys
  
  stop_requested = False    
  
  def sig_handler(signum, frame):
      sys.stdout.write("handling signal: %s\n" % signum)
      sys.stdout.flush()
  
      global stop_requested
      stop_requested = True    
  
  def run():
      sys.stdout.write("run started\n")
      sys.stdout.flush()
      while not stop_requested:
          time.sleep(2)
  
      sys.stdout.write("run exited\n")
      sys.stdout.flush()
  
  signal.signal(signal.SIGTERM, sig_handler)
  signal.signal(signal.SIGINT, sig_handler)
  
  t = Thread(target=run)
  t.start()
  t.join()
  sys.stdout.write("join completed\n")
  sys.stdout.flush()
  </code></pre>
  
  <p>I tested this in the following two ways:</p>
  
  <p>1)</p>
  
  <pre><code>$ python main.py &gt; output.txt&amp;
  [2] 3204
  $ kill -15 3204
  </code></pre>
  
  <p>2)</p>
  
  <pre><code>$ python main.py
  ctrl+c
  </code></pre>
  
  <p>In both cases I expect this written to the output:</p>
  
  <pre><code>run started
  handling signal: 15
  run exited
  join completed
  </code></pre>
  
  <p>In the first case the program exits but all I see is:</p>
  
  <pre><code>run started
  </code></pre>
  
  <p>In the second case the SIGTERM signal is seemingly ignored when ctrl+c is pressed and the program doesn't exit.</p>
  
  <p>What am I missing here?</p>