1

Is there a way to catch a signal just once with sigaction structure and function? To be more specific, I would like to simply reset to default a specific signal (SIGINT). Is it possible to achieve this in a handler?

Edit

So, something like this would be correct:

void sig_int(int sig)
{
    printf(" -> Ctrl-C\n");
    struct sigaction act;
    act.sa_handler = SIG_DFL;

    if(sigaction(SIGINT, &act, NULL) < 0)
    {
        exit(-1);
    }

}

int main()
{
    struct sigaction act;
    act.sa_handler = sig_int;

    if(sigaction(SIGINT, &act, NULL) < 0)
    {
        exit(-1);
    }

    while(1)
    {
        sleep(1);
    }

    return 0;   
}
4

3 回答 3

4

sa_flags在 的成员中设置的标准 SA_RESETHAND 标志struct sigaction正是这样做的。

在指定 SIGINT 处理程序时设置该标志,处理程序将在进入时重置为 SIG_DFL。

于 2016-11-01T21:07:50.563 回答
1

只需恢复程序中的默认操作即可。

struct sigaction old;
void sig_int(int sig)
{
        printf(" -> Ctrl-C\n");

        if(sigaction(SIGINT, &old, NULL) < 0)
        {
                exit(-1);
        }

}

int main()
{
        struct sigaction act;
        act.sa_handler = sig_int;

        if(sigaction(SIGINT, &act, &old) < 0)
        {
                exit(-1);
        }

        while(1)
        {
                sleep(1);
        }

        return 0;
}
于 2017-03-26T14:20:53.220 回答
1

是的,您可以sigaction在信号处理程序内部调用。这是由 Posix 指定的,它(在XBD 第 2.4.3 章中)“定义了一组应该是异步信号安全的函数”。然后它指出“应用程序可以不受限制地从信号捕获函数中调用它们。”。sigaction()在那个列表中。

于 2016-11-01T20:54:14.170 回答