ens*_*s91 12 c c++ linux signals
我应该覆盖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)
}
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这将捕获Ctrl-C(引发SIGINT),并且信号处理程序不会被替换,因此它每次都会触发,并且没有人终止程序.
请注意,信号处理程序由fork()ed children 继承.
Posix函数sigaction()允许您注册"一次性"处理程序,这些处理程序在调用一次后由标准处理程序替换.不过,这是更高级和Posix特有的.
编辑:正如@Dietrich指出的那样,你绝不应该在信号处理程序中做任何真正的工作.相反,你应该设置一个标志(我提供了一个例子),并检查你的循环中的那个标志(并在那里打印消息).我也会修改这个例子.