C++: Continue execution after SIGINT
c++, copy-paste, sigint, signals, windows
Solution
From MSDN:
Note SIGINT is not supported for any Win32 application, including Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application such as UNIX, to become multithreaded, resulting in unexpected behavior.
Which means you will have to use preprocessing directive and implement a Windows specific solution.
BOOL WINAPI handler(DWORD dwCtrlType)
{
if (CTRL_C_EVENT == dwCtrlType)
{
// ask the user
}
return FALSE;
}
And at the beginning of `main` you do
SetConsoleCtrlHandler(handler, TRUE);
Problem
Okay, I am writing a program that is doing some pretty heavy analysis and I would like to be able to stop it quickly. I added `signal(SIGINT, terminate);` to the beginning of main and defined terminate like: ``` void terminate(int param){ cout << endl << endl << "Exit [N]ow, or [A]fter this url?" << endl; std::string answer; cin >> answer; if(answer[0] == 'n' || answer[0] == 'N'){ terminateParser(); exit(1); }else if(answer[0] == 'a' || answer[0] == 'A'){ quitAfterUrl = true; } } ``` In linux, this worked as I expected it to, that is it waited for user input. But when I try to do the same in windows, it shows the message and exits anyway. Is there any way to stop SIGINT from closing the program immediately? Update: when I tried ``` BOOL WINAPI handler(DWORD dwCtrlType) { if (CTRL_C_EVENT == dwCtrlType) { // ask the user } return FALSE; } ``` as Gregory suggested, the program still unceremoniously exited without stopping for user input. Update 2: I am not exactly sure what did it, but the code is working now. Thank you all for the help.