Signal Handling in Windows

£可爱£侵袭症+ 提交于 2019-12-13 02:23:55

问题


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.

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)

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

os.kill(pid,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.

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

Thanks in advance.


回答1:


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

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

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



来源:https://stackoverflow.com/questions/26061814/signal-handling-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!