覆盖Ctrl-C

时间:2011-10-01 22:35:17

标签: c++ c linux signals

我应该覆盖 Ctrl C 信号并使用它来打印消息。它不应该结束该计划。

到目前为止,当按下 Ctrl C 时,它会打印消息,但会结束程序。

当我问我的教授他告诉我这样做时: 您需要让信号处理程序不再继续处理信号。现在,信号由您的代码处理,然后转到父处理程序。

我应该添加一个方法,还是需要在某个地方移动信号安装程序?

到目前为止,这是我的代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>  
#include <sys/types.h>
#include <signal.h> 
#include "Input.h"
#include "CircleBuff.h"

//void handler_function(int signal_id);

void catch_int(int sig_num){

    //reset the signal handler again to catch_int, for next time
    signal(SIGINT, catch_int);
    //print message
    printf("Print History");
    fflush(stdout);
}

void printHistory(CircleBuff hist){
    cout << "Complete History:\n" << endl;
    hist.print();
    cout << endl;
}

int main(int argc, char** argv){

  struct sigaction signal_action;                /* define table */
  signal_action.sa_handler = catch_int;   /* insert handler function */
  signal_action.sa_flags = 0;                    /* init the flags field */
  sigemptyset( &signal_action.sa_mask );     /* are no masked interrupts */
  sigaction( SIGINT, &signal_action, NULL ); /* install the signal_action */

  do{


  //My code: where the value report will be assigned within.

  } while(report != 1)

}

2 个答案:

答案 0 :(得分:10)

哇,方式过多的代码来筛选。但是,如果使用C标准库,则应获得所需的行为。这是一个C ++版本:

#include <iostream>
#include <csignal>

sig_atomic_t sigflag = 0;

void sighandler(int s)
{
  // std::cerr << "Caught signal " << s << ".\n"; // this is undefined behaviour
  sigflag = 1; // something like that
}

int main()
{
  std::signal(SIGINT, sighandler);

  // ... your program here ...

  // example: baby's first loop (Ctrl-D to end)
  char c;
  while (std::cin >> c)
  {
    if (sigflag != 0) { std::cerr << "Signal!\n"; sigflag = 0; }
  }
}

这将捕获Ctrl-C(引发SIGINT),并且信号处理程序不会被替换,因此每次都会触发,并且没有人终止该程序。

请注意,信号处理程序由fork() ed孩子继承。

Posix函数sigaction()允许您注册“一次性”处理程序,这些处理程序在调用一次后由标准处理程序替换。不过,这是更高级和特定于Posix的。

编辑:正如@Dietrich所指出的那样,你不应该在里面做任何真正的工作一个信号处理程序。相反,你应该设置一个标志(我提供了一个例子),并检查你的循环中的那个标志(并在那里打印消息)。我也会修改这个例子。

答案 1 :(得分:0)

您是否认为在while循环内部可能存在可中断的功能,并且无法使用'EINTR'。您可以使用以下方法修复它:

sa.sa_flags = SA_RESTART;

或者,只需检查errno并循环播放。你确定程序没有到达终止结束。尝试在main的末尾放置一个print语句。

相关问题