2

I have a subprocess opened with Popen. When I press CTRL+C in the main program, my subprocess shutdowns just fine with the handler I registerd for SIGINT and SIGTERM. However: When I try to manually send SIGINT, it raises a signal not supported error. Sending SIGTERM kills my subprocess instantly. When I do handle.terminate(), my subprocess just dies, too.

I need it to shutdown gracefully. I searched and searched and couldnt find anything which would replicate the behavior from pressing CTRL+C.

Is there anything I can do, to achieve what I want?

As stated in the title, i am using windows (7 64bit, python 3.4.5)

// EDIT: I also tried sending CTRL_C_EVENT which is possible but cant be registered as signal handler in the subprocess

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
  • `CTRL_C_EVENT` and `CTRL_BREAK_EVENT` are console control events -- not POSIX signals. Console control events originate in the console host process (conhost.exe) and get relayed by the session Windows server (csrss.exe) to processes attached to a given console by injecting a thread in each process that starts execution at the known entry point `kernel32!CtrlRoutine`. This executes the list of handlers registered via `SetConsoleCtrlHandler`. The C runtime installs a handler that calls its `SIGINT` and `SIGBREAK` handlers for `CTRL_C_EVENT` and `CTRL_BREAK_EVENT`, respectively. – Eryk Sun Nov 23 '16 at 11:36
  • You can send a control event to other processes attached to the current console via `GenerateConsoleCtrlEvent`, which is what Python `os.kill` calls for `CTRL_C_EVENT` and `CTRL_BREAK_EVENT`. (For all other values it calls `TerminateProcess`.) This targets a process group. Group ID 0 broadcasts the event to all processes attached to the console. To create a new group, pass `creationflags=CREATE_NEW_PROCESS_GROUP` to `subprocess.Popen`. The group ID is the PID of the root process. – Eryk Sun Nov 23 '16 at 11:47
  • 1
    The `CREATE_NEW_PROCESS_GROUP` flag causes Ctrl+C to be disabled. It would have to be enabled manually in the child process via `SetConsoleCtrlHandler(NULL, FALSE)`. However, Ctrl+Break can't be disabled, so you can always send `CTRL_BREAK_EVENT` to a process group. – Eryk Sun Nov 23 '16 at 11:51
  • See my answer [here](http://stackoverflow.com/a/35792192/205580) for more detail. – Eryk Sun Nov 23 '16 at 12:08

0 Answers0