6

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.

5
  • Try moving the while loop inside the try block. Commented Jun 18, 2015 at 14:24
  • @piedar It didn't work. Commented Jun 18, 2015 at 14:27
  • 2
    Because threads cannot listen to signals; only the main thread can. Commented Jun 18, 2015 at 14:30
  • @JamesMills Thanks for the help. I didn't know that. I've tested my code my listening in to the interrupt in the main thread and it worked. Commented Jun 18, 2015 at 14:34
  • No problems! See my answer below. Commented Jun 18, 2015 at 14:35

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.