在sigaction处理ctrl + c aka SIGINT之后等待输入的正确方法

时间:2015-08-12 15:31:26

标签: c++ c++11 sigaction

此程序将无限打印"输入:"通过 Ctrl + C 发送SIGINT后到命令行。要退出此循环,我使用 Ctrl + \ 。如果我取消注释包含std::cin.clear();的行,一切正常。我的问题是,这是正确的方法吗?人们必须在他希望程序等待的每个cin / cout前面设置std::cin.clear();。这就是为什么它似乎不适合我。

#include<iostream>
#include<signal.h>

void sig_handler(int s)
{
  std::cout << "Cought: " << s << std::endl;
  // do something...
}


int main ()
{
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = sig_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);
  int a=1;
  while(a)
    {
      std::cout << "Enter a:" << std::endl;
      //std::cin.clear(); // Uncomment me!
      std::cin >> a;
    }
}
PS:我知道信号处理程序中的cout是个坏主意。

PPS:当我使用旧的(已弃用的)std::cin.clear();时,一切正常(没有signal())。

PPPS:为了说清楚,我不想在 Ctrl + C 退出程序!

0 个答案:

没有答案