sigaction 只处理一次信号

sigaction handle signal just once

有没有办法用 sigaction 结构和函数只捕获一次信号?更具体地说,我想简单地重置为默认特定信号 (SIGINT)。是否有可能在处理程序中实现这一点?

编辑

所以,这样的事情是正确的:

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

是的,您可以在信号处理程序中调用 sigaction。这是由 Posix 指定的,其中(在 XBD chapter 2.4.3 中)"defines a set of functions that shall be async-signal-safe." 然后指出 "applications can call them, without restriction, from signal-catching functions. "。 sigaction() 在该列表中。

The standard SA_RESETHAND flag,设置在 struct sigactionsa_flags 成员中,正是这样做的。

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

恢复程序默认动作即可

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