Python - catching signals between sleep calls

So let's say I have this code:

import signal from time import sleep def signalHandler(sig, frame): print "signalHandler" while True: sleep(1) #print "Caught" # Uncomment this line, and you get multiple signals - commented, you don't. signal.signal(signal.SIGINT, signalHandler) while True: sleep(1) 

As you can see from the comment, if the print statement is uncommented, the code works fine, and the signal handler will catch any subsequent CTRL-C presses, as it should be. However, if you leave a comment, another signal will never be caught.

Why is this? I assume that consecutive sleep calls are stretched together and control never returns to the python to catch the signal. What it would have to do for a press statement. Can anyone shed some light on this?

+6
source share
1 answer

This is really weird!

I believe this is a subtle interaction between the internal components of the generated Python bytecode and the anomalies that have been present in Python 2.7 before. Pay attention to two things:

  • Your code works fine in Python 3 with or without print instructions.
  • If you change the sleep inside the signal handler to "sleep (60)", you will notice that it still works correctly if you press Ctrl-C before printing is reached! (That's what made me suspicious).

If you read Issue 12472 in the Python bug tracker , you will see that Python inserts the Py_CheckSleep internal call until the next instruction (in this case, your print), which causes the signal to be caught when sleep is interrupted. Without printing, additional verification does not occur.

According to this problem, this was fixed in Python 3 and later, but not in earlier versions.

+1
source

Source: https://habr.com/ru/post/989858/


All Articles