Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why monitoring a keyboard interrupt in python thread doesn't work

I have a very simple python code:

def monitor_keyboard_interrupt():

  is_done = False 

  while True:
    if is_done
      break
    try:
      print(sys._getframe().f_code.co_name)
    except KeyboardInterrupt:
      is_done = True

def test():
  monitor_keyboard_thread = threading.Thread(target = monitor_keyboard_interrupt)
  monitor_keyboard_thread.start()
  monitor_keyboard_thread.join()

def main():
  test()

if '__main__' == __name__:
  main()

However when I press 'Ctrl-C' the thread isn't stopped. Can someone explain what I'm doing wrong. Any help is appreciated.

like image 263
flashburn Avatar asked Jun 18 '15 14:06

flashburn


1 Answers

Simple reason:

Because only the <_MainThread(MainThread, started 139712048375552)> can create signal handlers and listen for signals.

This includes KeyboardInterrupt which is a SIGINT.

THis comes straight from the signal docs:

Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead.

like image 50
James Mills Avatar answered Nov 15 '22 08:11

James Mills