multithreading - Interrupt signals awake Python process from sleeping and continue where it left off? -
the following code print out current time every 5 seconds, , handles keyboard interrupt signals int_handler
.
from signal import * import time datetime import datetime def int_handler(*args): print 'interrupted' signal(sigint, int_handler) while true: print datetime.now() time.sleep(5)
however, every time press ctrl-c print out current time immediately, , continue running.
2016-06-28 18:17:19.441574 2016-06-28 18:17:24.446659 2016-06-28 18:17:29.451759 2016-06-28 18:17:34.452328 ^cinterrupted 2016-06-28 18:17:37.244227 ^cinterrupted 2016-06-28 18:17:37.692217 ^cinterrupted 2016-06-28 18:17:38.236343 ^cinterrupted 2016-06-28 18:17:38.572194 2016-06-28 18:17:43.577122 2016-06-28 18:17:48.577242
it seems interruption awakes process sleeping, handler gets executed, , somehow gets while loop again.
can explain me why? thanks!
from documentation of sleep()
:
the actual suspension time may less requested because caught signal terminate sleep() following execution of signal’s catching routine.
https://docs.python.org/3/library/time.html#time.sleep
so describe happening: after handling signal in signal handler execution continues after sleep, last expression in while-loop.
hence in order sleep approximately 5 seconds ignoring interruptions you'd have store time before sleep , check on waking enough has passed, or sleep more.
Comments
Post a Comment