简体   繁体   中英

Confusion over time.sleep in Python “while True” loop

Level beginner I am using python 2.7 version on ubuntu. I have a confusion regarding a small code snippet in python. I know that while True in python means to loop infinitely. I have the following code:

#!/usr/bin/env python
import signal
import time

def ctrlc_catcher(signum, frm):
     print "Process can't be killed with ctrl-c!"

def alarm_catcher(signum,frame):
    print "Got an alarm"


signal.signal(signal.SIGINT, ctrlc_catcher)
signal.signal(signal.SIGALRM, alarm_catcher)


while True:
   signal.alarm(1)
   pass

When I execute the programm the output is blank, when I hit Ctrl-C key it displays "Process can't be....." message. My question is why the signal.alarm(1) is not working ? However if I put a small pause using

while True:
   signal.alarm(1)
   time.sleep(1)
   pass

after it then the alarm gets triggered and in the output screen I see "Got an alarm" message after every second. What is time.sleep(1) doing so that the alarm gets triggered? Thanks

In the first example you're constantly resetting the alarm. You set an alarm for 1 second from now, then 0.00001 seconds later you set an alarm for 1 second from now, then 0.00001 seconds later you set an alarm for 1 second from now... so the alarm is always 1 second in the future! In the second example, by sleeping, you allow 1 second to pass before you reset the alarm, so it actually has time to go off.

I think what you meant to write in your first example was

signal.alarm(1)
while True:
    pass

The problem is that you are over writing your alarms. The following is from the signal docs :

signal.alarm(time)

If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM