Tuesday, May 2, 2017

"Signal" Handling in Windows Console Application

Signal handling in Windows console application is quite different from what POSIX defines. Well, you could do it the POSIX way if you're using Visual Studio (see: signal). But, the behavior is not quite like POSIX in all circumstances. The Windows native "signal" handling is the way to go if you're using third party compiler suite or cross-compiling via MinGW-W64. The native "signal" handling is also known as Windows Console Control Handlers. The Console Control Handlers are "reachable" via native Windows API.

There is a peculiarity in Windows Console Control Handler compared to the way POSIX handle CTRL+C (SIGINT) signal. In Windows, a new thread is created by Windows which invoke the registered control handler to process the signal, see: CTRL+C and CTRL+BREAK Signals. Contrary, in POSIX, the OS doesn't run the signal handler in a new thread.

Now, let's look at how you would implement a native Windows signal handler for console application. The Windows API that you need is: SetConsoleCtrlHandler(). As for, how to use the function, MSDN has it covered: Registering a Control Handler Function. FYI, I have tested part of the routine with Mingw-w64 cross compiler suite and run the executable in Windows 10. I confirmed that it works as "advertised".
Post a Comment

No comments: