Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal Handling in Windows

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.

like image 765
karthi_ms Avatar asked Sep 26 '14 14:09

karthi_ms


1 Answers

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.

like image 173
Marc Avatar answered Sep 30 '22 14:09

Marc