Windows 中的信号处理

kar*_*_ms 6 python windows signals python-2.7 python-3.x

在 Windows 中,我试图创建一个等待 SIGINT 信号的 python 进程。当它接收到 SIGINT 时,我希望它只打印一条消息并等待 SIGINT 的另一次出现。所以我使用了信号处理程序。

这是我的 signal_receiver.py 代码。

import signal, os, time

def handler(signum, frame):
    print 'Yes , Received', signum

signal.signal(signal.SIGINT, handler)
print 'My process Id' , os.getpid()

while True:
    print 'Waiting for signal'
    time.sleep(10)
Run Code Online (Sandbox Code Playgroud)

当这个进程运行时,我只是使用其他 python 进程将 SIGINT 发送到这个进程,

os.kill(pid,SIGINT).

但是当 signal_receiver.py 收到 SIGINT 时,它只是退出执行。但预期的行为是在处理程序函数中打印消息并继续执行。

有人可以帮我解决这个问题吗?这是 Windows 中的限制吗,因为在 linux 中同样可以正常工作。

提前致谢。

Mar*_*arc 4

当您按 CTRL+C 时,进程会收到 SIGINT,并且您可以正确捕获它,否则会引发错误KeyboardInterrupt

在 Windows 上,当time.sleep(10)被中断时,虽然你捕获了 SIGINT,但它仍然会抛出一个InterruptedError. 只需在 time.sleep 中添加一条 try/ except 语句即可捕获此异常,例如:

import signal
import os
import time

def handler(signum, frame):
    if signum == signal.SIGINT:
        print('Signal received')

if __name__ == '__main__':
    print('My PID: ', os.getpid())
    signal.signal(signal.SIGINT, handler)

    while True:
        print('Waiting for signal')
        try:
            time.sleep(5)
        except InterruptedError:
            pass
Run Code Online (Sandbox Code Playgroud)

注意:在 Python3.x 上测试,它也应该在 2.x 上工作。