C ++:在SIGINT后继续执行 [英] C++: Continue execution after SIGINT

查看:174
本文介绍了C ++:在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.

我添加了 signal(SIGINT,terminate); 到main的开头并定义终止如:

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;
   }
}



在linux中,即等待用户输入。

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.

有没有办法阻止SIGINT立即关闭程序?

Is there any way to stop SIGINT from closing the program immediately?

更新:

当我尝试

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.

更新2:
我不知道是什么,但是代码现在正在工作。感谢大家的帮助。

Update 2: I am not exactly sure what did it, but the code is working now. Thank you all for the help.

推荐答案

从MSDN:


注意 SIGINT不适用于任何Win32应用程序,包括Windows 98 / Me和Windows NT / 2000 / XP。当发生CTRL + C中断时,Win32操作系统会生成一个新的线程来专门处理该中断。这可能会导致单线程应用程序(如UNIX)变为多线程,导致意外的行为。

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.

这意味着您必须使用预处理指令并实施 Windows特定解决方案

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;
}

并在 main 你做

SetConsoleCtrlHandler(handler, TRUE);

这篇关于C ++:在SIGINT后继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆