简体   繁体   中英

signal.SIGINT in windows cause process exit directly

I wrote those test python code as following:

import signal
import time
import os

def handler(signum, frame):
    print "do whatever, like call thread.interrupt_main()"
    return

signal.signal(signal.SIGINT, handler)

while 1:
    try:
        time.sleep(10)
    except:
        os.kill(int(os.getpid()), signal.SIGINT)
        pass

when i excute this test code on windows, the process print "do whatever, like call thread.interrupt_main()", then exit; on linux, it works correctly.

why on windows it not work?

http://docs.python.org/2/library/os.html#os.kill

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, eg, some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig.

Try following code:

import time

while 1:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        print "do whatever, like call thread.interrupt_main()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM