【发布时间】:2017-01-27 00:55:09
【问题描述】:
我正在尝试修改以下代码以使用 sigaction() 拦截 SIGINT;
我需要将“for”循环替换为“while(1);你应该可以通过输入“^\”退出程序。(需要拦截SIGQUIT。)
#include <signal.h>
#include <unistd.h>
#include <iostream>
using namespace std;
void func ( int sig )
{
cout << "Oops! -- I got a signal " << sig << endl;
}
int main()
{
(void) signal ( SIGINT, func ); //catch terminal interrupts
//for ( int i = 0; i < 20; ++i )
while(1)
{
cout << "signals" << endl;
sleep ( 1 );
}
return 0;
}
【问题讨论】:
-
SIGINT 还是 SIGQUIT?是哪一个?
-
您需要使用正确的信息设置
struct sigaction变量。然后您调用sigaction()而不是signal()。其余大部分保持不变。请注意,在信号处理程序中调用cout << …很可能是“未定义的行为”。见How to avoid usingprintf()in a signal handler。它只适用于 C,但类似的概念也适用于 C++。
标签: c++ operating-system signals