简体   繁体   中英

Signal handling in loop with sleep python 2.7

This might be a simple situation that I expect many would have encountered it. I have a simple python program that does something and sleeps for sometime in an infinite loop. I want to use signals to make this program exit gracefully on a SIGHUP. Now when a signal is sent to callee.py when it is in sleep, the program exits immediately whereas I expect it to finish the sleep and then exit.

Is there any workaround to bypass this behavior? I am also open to any other methods through which I can achieve this.

Note: This works as expected with python3 but I cannot port my existing module which is in python 2.7 to 3 now.

This is the code I have:

callee.py

stop_val = False
def should_stop(signal, frame):
    print('received signal to exit')
    global stop_val
    stop_val = True

def main():
    while not stop_val:
        signal.signal(signal.SIGTERM, should_stop)
        # do something here
        print('Before sleep')
        time.sleep(300)
        print('after sleep')

caller.py

pid = xxx;
os.system('kill -15 %s' % pid)

I ran into the same issue today. Here is a simple wrapper that mimicks the python3 behaviour:

def uninterruptable_sleep(seconds):
    end = time.time()+seconds
    while True:
        now = time.time() # we do this once to prevent race conditions
        if now >= end: 
            break
        time.sleep(end-now)

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