views:

261

answers:

2

I have a console deamon that is runned by a GUI application. When the GUI application is terminated I'd like to stop the deamon 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 details: the deamon app is written in python and the gui is written in C# & windows forms.

A: 

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.

Seva Alekseyev
I don't have any two way communication implemented. I just using stdout. It is why I've asked the question :)
Piotr Czapla
Well then, the short answer is that there are no signals, but many other interprocess communication mechanisms. But most of them require cooperation on both ends. The one that does not is TerminateProcess().
Seva Alekseyev
I've finally created a named shared memory and used it as a way to communicate with the gui.
Piotr Czapla
+1  A: 

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.

Kevin Montrose
GenerateConsoleCtrlEvent() should work from outside the process. Pass the PID.
Hans Passant
I am glossing over things a bit, but dwProcessGroupId != PID in the purest sense.
Kevin Montrose
CtrlEvent looks like the solution let me try it.
Piotr Czapla
There is even a blog about this: http://danielkaes.wordpress.com/2009/06/04/how-to-catch-kill-events-with-python/
Piotr Czapla