[英]How can i use sigaction() to intercept SIGINT?
I am trying to modify the following code to use sigaction() to intercept SIGINT; 我试图修改以下代码以使用sigaction()拦截SIGINT;
I need to replace the "for" loop with "while ( 1 ); you should be able to quit the program by entering "^\\". (Need to intercept SIGQUIT.) 我需要将“ 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;
}
You can use sigaction
to catch SIGINT
(and still have the output you've described) with the following code (which compiles and works for me using clang on a Unix like OS): 您可以使用sigaction
通过以下代码捕获SIGINT
(并仍然具有您描述的输出)(以下代码在OS等Unix上使用clang编译并为我工作):
#include <signal.h>
#include <iostream>
#include <unistd.h>
static int sigcaught = 0;
static void sighandler(int signum)
{
sigcaught = signum;
}
int main()
{
int signum = SIGINT;
struct sigaction newact;
struct sigaction oldact;
newact.sa_handler = sighandler;
sigemptyset(&newact.sa_mask);
newact.sa_flags = 0;
sigaction(signum, &newact, &oldact);
while (!sigcaught)
{
std::cout << "waiting for signal" << std::endl;
sleep(1);
}
std::cout << "Oops! -- I got a signal " << sigcaught << std::endl;
return 0;
}
Please note that: this code intentionally isn't checking return values (like from sigaction
nor sleep
) since the original code isn't and since checking them may detract a reader from seeing the relevant differences. 请注意:由于原始代码不是,此代码有意不检查返回值(例如来自sigaction
或sleep
返回值),并且因为检查它们可能会使读者看不到相关的差异。 I would not want production code to ignore return values however (particularly those that can indicate errors). 我不希望生产代码忽略返回值(特别是那些可能指示错误的返回值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.