Reputation: 786
I'm using the latest update of Visual Studio 2019 (Version 16.5.0 Preview 2.0) and trying to intercept the control-c event. But for some reason the console program always crashes before calling my handler. By the way, the program crashes if even I don't install any handler.
Could this be a bug in the compiler? In general, how do you debug something like this?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <cstdint>
uint64_t iterations;
bool running;
BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType) {
case CTRL_C_EVENT: {
running = false;
return TRUE;
} break;
default: {
return FALSE;
} break;
}
}
int main()
{
if (!SetConsoleCtrlHandler(CtrlHandler, TRUE)) {
std::cout << "Could not install control handler" << std::endl;
}
running = true;
while (running) {
iterations++;
}
std::cout << "Terminated after " << iterations << " iterations." << std::endl;
return 0;
}
Upvotes: 1
Views: 914
Reputation: 165
https://learn.microsoft.com/en-us/windows/console/setconsolectrlhandler
Here it says that if an application is being debugged, "the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger". Hence it isn't chrashing; you can continue excectution and it should work fine. The documentation says:
If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed.
Upvotes: 3