title: Terminate sudo python script when the terminal closes
body: <p>How can I tell if the terminal running my python script was closed? I want to safely end my python script if the user closes the terminal. I can catch SIGHUP with a handler, but not when the script is run as sudo. When I start the script with sudo and close the terminal, the python script keeps running.</p>
  
  <p>Example script:</p>
  
  <pre><code>import signal
  import time
  import sys
  
  def handler(signum, frame):
      fd = open ("tmp.txt", "a")
      fd.write(str(signum) + " handled\n")
      fd.close()
      sys.exit(0)
  
  
  signal.signal(signal.SIGHUP, handler)
  signal.signal(signal.SIGINT, handler)
  signal.signal(signal.SIGTERM, handler)
  
  time.sleep(50)
  </code></pre>
  
  <p>Sometimes the script will execute the handler when run as sudo, but more often it doesn't. The script always writes to the file when ran without sudo. I am running it on a Raspberry Pi. I see the same thing in a LXTerminal and a gnome-terminal. This example script will end after 50 seconds, but my lengthy code runs in an infinite loop</p>
  
  <p>The ultimate goal is to have a .desktop launcher on a Raspberry Pi to do bluetooth scanning and find devices. The bluetooth scanning requires sudo because it use 4.0 BLE. I'm not sure why bluez requires sudo but it does. When type sudo on the pi, it never asks for a password which is fine with me. The problem is that after closing the terminal, the scan process is still running. The scanning is done by a python script that runs  in a terminal.</p>