0

In python script below, i am trying to catch SIGTERM signal (which may recived from other process) by installing my isr and overriding python default one. while this script works great in linux (not surprising), in windows it doesn't work (not surprising)!

How can i get the same behavior in windows 7?

Iam runing python 2.7 on windows 7 PC.

import os
import signal
import time


def instal_isr(SIGN, isr):
    signal.signal(SIGN, isr)


def sigterm_isr(SIGN, int_stack_frame):
    print 'received SIGTERM, {sign} {stackframe}'.format(sign=SIGN, stackframe=int_stack_frame)
    #do some stuf and exit
    exit(1)


def main():
    while(True):
        print 'wasting your cpu cycles'
        time.sleep(2)


if __name__=='__main__':
    instal_isr(signal.SIGTERM, sigterm_isr)
    main()

The output in Linux:

wasting your cpu cycles
wasting your cpu cycles
wasting your cpu cycles
wasting your cpu cycles
received SIGTERM, 15 <frame object at 0x7f6261852dd0>

I have tried to get relevant information from the question in the link signal handling python on windows machine , the responds dived into details and not actually covers this "simple" case.

Adam
  • 2,820
  • 1
  • 13
  • 33
  • The linked answer states that "Windows doesn't implement signals at the system level"; and "Microsoft's C runtime implements the six signals that are required by standard C: SIGINT, SIGABRT, SIGTERM, SIGSEGV, SIGILL, and SIGFPE"; but "SIGABRT and SIGTERM are implemented just for the current process"; and "SIGTERM is useless". – Eryk Sun Apr 27 '20 at 23:26
  • How are you killing the Python process? If it's via `TerminateProcess`, there is nothing to handle. That's like Unix SIGKILL. The kernel process manager unconditionally terminates the process without notice -- at least without notice to user-mode code. – Eryk Sun Apr 27 '20 at 23:26
  • I will try to be more precise. is there any way to catch in python script killing signal that have been fired by one of those windows commands/tools: 1. taskkill [python_script_pid] /F /T 2. wmic via call terminate command 3. kill -f -s KILL [python_script_pid] – Adam Apr 28 '20 at 08:18
  • WMI terminate and taskkill with `/f` are both forced termination, i.e. `TerminateProcess`. They cannot be handled. taskkill without `/f` tries to send a `WM_CLOSE` window message to top-level and message-only windows that are owned by a process. A console window is effectively owned by the process that allocates the console session. As to `kill`, is that an MSYS2 build of Cygwin kill? If so, I'd assume it calls `TerminateProcess` since Windows doesn't have Unix signals. – Eryk Sun Apr 28 '20 at 09:21

0 Answers0