【发布时间】:2011-10-01 22:35:16
【问题描述】:
我应该覆盖 CtrlC 信号并使用它来打印消息。它不应该结束程序。
到目前为止发生的情况是,当按下 CtrlC 时,它会打印消息,但会结束程序。
当我问我的教授时,他告诉我这样做: 您需要让您的信号处理程序不再继续处理信号。现在信号正在由您的代码处理,然后转到父处理程序。
是否有我应该添加的方法或者我需要将信号安装程序移动到某个地方?
这是我目前的代码:
#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)
}
【问题讨论】:
-
您不应该从信号处理程序内部调用
printf,因为printf不是异步安全的。有关异步安全函数的列表,请参阅man 7 signal。更简单的write系统调用是异步安全的,但<stdio.h>函数都不是。