Windows 中的信号处理 [英] Signal Handling in Windows

查看:42
本文介绍了Windows 中的信号处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Windows I am trying to create a python process that waits for SIGINT signal.And when it receives SIGINT I want it to just print a message and wait for another occurrence of SIGINT.So I used signal handler.

这是我的 signal_receiver.py 代码.

Here is my signal_receiver.py code.

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)

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

When this process running ,I just send SIGINT to this procees from some other python process using,

os.kill(pid,SIGINT).

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

But when the signal_receiver.py receives SIGINT it just quits the execution .But expected behavior is to print the message inside the handler function and continue execution.

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

Can some one please help me to solve this issue.Is it a limitation in windows ,because the same works fine in linux.

提前致谢.

推荐答案

当你按下 CTRL+C 时,进程会收到一个 SIGINT 并且你正在正确地捕捉它,否则它会抛出一个 KeyboardInterrupt错误.

When you press CTRL+C, the process receives a SIGINT and you are catching it correctly, because otherwise it would throw a KeyboardInterrupt error.

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

On Windows, when time.sleep(10) is interrupted, although you catch SIGINT, it still throws an InterruptedError. Just add a try/except statement inside time.sleep to catch this exception, for example:

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

注意:在 Python3.x 上测试过,应该也适用于 2.x.

Note: tested on Python3.x, it should also work on 2.x.

这篇关于Windows 中的信号处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆