Signal Handling in Windows

11,893

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.

Share:
11,893
karthi_ms
Author by

karthi_ms

A True Techie :)

Updated on June 30, 2022

Comments

  • karthi_ms
    karthi_ms almost 2 years

    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.