如何使用 sigaction() 拦截 SIGINT

How can i use sigaction() to intercept SIGINT?

本文关键字:拦截 SIGINT 何使用 sigaction      更新时间:2023-10-16

我正在尝试修改以下代码以使用 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;
}

您可以使用sigaction使用以下代码(在类似操作系统的Unix上使用clang编译和工作)来捕获SIGINT(并且仍然具有您描述的输出):

#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;
}

请注意:此代码故意不检查返回值(例如来自sigactionsleep),因为原始代码不是,并且检查它们可能会分散读者看到相关差异的注意力。但是,我不希望生产代码忽略返回值(尤其是那些可以指示错误的值)。