Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a posix SIGTERM alternative on Windows? - (A gentle kill for console application)

I have a console daemon that is run by a GUI application. When the GUI application is terminated I'd like to stop the daemon as well.

How can I do it in a gentle way on windows?

On Linux, I would just use SIGTERM is there a similar mechanism on windows for console applications?

To provide a bit more detail, the daemon app is written in python and the gui is written in C# & windows forms.

like image 777
Piotr Czapla Avatar asked Jan 05 '10 16:01

Piotr Czapla


2 Answers

Define "gentle" :)

I'm assuming there is already a communication mechanism in place between the daemon and the GUI. Just introduce a "quit" command and send it.

If you want to kill the daemon even if it's busy doing something (or is frozen), use TerminateProcess().

To have the best of both, you can send "quit", then wait on the process handle for some time (WaitForSingleObject()). If the daemon process does not die in, say, 5 sec, then terminate it.

If the main thread of the daemon is prone to long periods of busy activity, have the daemon start a background thread that does nothing but waits for a named event. To signal that thread, open the event by name from GUI, then raise it. It's up to the daemon what to do upon event detection, but at least it will be a controlled shutdown.

like image 130
Seva Alekseyev Avatar answered Oct 18 '22 12:10

Seva Alekseyev


Windows doesn't have signals in the way you're thinking.

There's some infrastructure for changing how the (faked) SIGTERM and SIGBREAK are handled by console apps, mostly SetConsoleCtrlHandler and GenerateConsoleCtrlEvent but both are only of use in the console application itself; not from outside.

It's worth noting that all a windows console app does when it receives a SIGTERM is call ExitProcess, nothing special. I'm not 100% on what the python equivalent is called, but whatever standard "exit" call should be equivalent.

I'd suggest writing some code to signal the console app, causing it to call ExitProcess itself. If that's not an option, use TerminateProcess (equivalent Process.Kill) to close the console process from the outside; attempting to "fake" an ExitProcess is dangerous for reasons noted in the MSDN article.

like image 31
Kevin Montrose Avatar answered Oct 18 '22 11:10

Kevin Montrose