开发者

C++: Continue execution after SIGINT

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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜