views:

420

answers:

1

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.

+7  A: 

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);
Gregory Pakosz
As a note: is his situation allows, compiling with gcc for windows might prevent the rewrite of the solution.
laura
I was afraid of that.
zipcodeman
@laura - I am already using gcc
zipcodeman
I guess this is my best option.
zipcodeman
I don't recall any other way and well the note about `SIGINT` makes it pretty clear
Gregory Pakosz
I usually have a common SIGINT stub for both Windows and other operating systems. This way, I'm able to call the common stub from the various OS-specific event handlers and avoid code duplication.
Matthew Iselin
I have been running this application from MSYS with MinGW32. but when i tried it under windows command prompt, it worked fine. thank you.
zipcodeman