poundifdef
poundifdef

Reputation: 19353

Why does this quit immediately on SIGKILL?

When I press Ctrl-C, the following code terminates immediately.

However, it seems that the loop should exit after a 10 second delay - because it is not checking the status of keep_going until we reach the top of the loop. Why is this code exiting the loop immediately?

How would I make sure that the loop finishes execution before exiting?

import signal
import time

keep_going = True

def signal_handler(signal, frame):
    global keep_going
    print 'quitting!'
    keep_going = False

signal.signal(signal.SIGINT, signal_handler) 

while keep_going:
    print 'looping...'
    time.sleep(10)
    print 'bye!'

Upvotes: 1

Views: 284

Answers (2)

Keith
Keith

Reputation: 43024

The signal interrupts the sleep call, continues with the loop, the condition is False, so it terminates the loop. Python does not resume the sleep call.

BTW, the Python interpreter normally catches SIGINT itself, and translates that to a KeyboardInterrupt exception that you can catch instead of using the signal module.

Upvotes: 2

Amadan
Amadan

Reputation: 198324

From Python docs:

The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine.

I.e. the loop does finish its execution (as you can see from the "bye" being output after the signal handler's "quitting!"), it's just sleep that is cut short.

If you had something more substantial than sleep, I believe you'd see what you originally wanted.

Upvotes: 3

Related Questions