16

Under POSIX OS there is signal API that allows to send a signal to process to shut it down with kill and you can catch it with sigaction and do what you need;

However, Win32 is not POSIX system, so:

  • How can I handle shutdown events that may come, for example from "End Process" in "Task manager"?
  • What is the standard API for sending shutdown signal to Win32 application?

I'm not talking about GUI, I'm talking about TCP/IP server that should be nicely shutdown. that does not run like windows service.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
Artyom
  • 31,019
  • 21
  • 127
  • 215

3 Answers3

8

MSDNs Unix Code Migration Guide has a chapter about Win32 code conversion and signal handling.
Although Microsoft has decided to archive this brilliant guide, it is very useful.

Three methods are described:
Native signals
Event objects
Messages

Community
  • 1
  • 1
Kb.
  • 7,240
  • 13
  • 56
  • 75
5

You get a WM_QUIT message on your first created thread.

When you don't handle that, your process is forcibly shutdown.

So just implement a message queue in your first thread, which looks for the WM_QUIT message

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
Christopher
  • 8,912
  • 3
  • 33
  • 38
  • 2
    You should handle WM_CLOSE. "The WM_QUIT message is not associated with a window and therefore will never be received through a window's window procedure. It is retrieved only by the GetMessage or PeekMessage functions." -MSDN – Indy9000 Aug 01 '09 at 15:46
  • Can I use same method for Console Ctrl+C and for process runnig as Windows service? Or I should use different methods for each one of them? – Artyom Aug 01 '09 at 18:08
  • You can use **taskkill /im your_program.exe** to send a termination signal to the application. It will trigger a **WM_CLOSE** in windows message queue as @Indy9000 mentioned. – amilamad Apr 12 '19 at 02:02
3

May be Windows Power Management from MSDN would be helpful. But it deals with system events rather than per process.

For a process, you would be able to detect termination with WM_CLOSE. You would need to handle windows messages. If it's a console application you would need to install a control handler; take a look at SetConsoleCtrlHandler on MSDN

Indy9000
  • 8,651
  • 2
  • 32
  • 37