【问题标题】:Interrupt signals awake Python process from sleeping and continue where it left off?中断信号将 Python 进程从睡眠中唤醒并从中断处继续?
【发布时间】:2024-01-08 09:31:01
【问题描述】:

以下代码将每 5 秒打印一次当前时间,并使用int_handler 处理键盘中断信号。

from signal import *
import time
from datetime import datetime


def int_handler(*args):
    print 'interrupted'

signal(SIGINT, int_handler)

while True:
    print datetime.now()
    time.sleep(5)

但是,每次我按 Ctrl-C 时,它都会立即打印出当前时间,并继续运行。

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

似乎中断将进程从睡眠中唤醒,处理程序被执行,不知何故又回到了while循环。

谁能给我解释一下为什么?谢谢!

【问题讨论】:

    标签: python multithreading operating-system signals interrupt


    【解决方案1】:

    来自sleep()的文档:

    实际的挂起时间可能少于请求的时间,因为任何捕获的信号都会在执行该信号的捕获例程后终止 sleep()。

    https://docs.python.org/3/library/time.html#time.sleep

    所以你所描述的正是正在发生的事情:在你的信号处理程序中处理信号之后,在睡眠之后继续执行,这是你的 while 循环中的最后一个表达式。

    因此,为了在忽略干扰的情况下真正睡大约 5 秒,您必须存储睡眠前的时间并检查醒来是否已经足够,或者再睡一会儿。

    【讨论】: