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;   
}
Papipone
  • 1,083
  • 3
  • 20
  • 39

3 Answers3

4

The standard SA_RESETHAND flag, set in the sa_flags member of struct sigaction, does precisely this.

Set that flag when specifying your SIGINT handler, and the handler will be reset to SIG_DFL upon entry.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
  • I don't know why, but I don't have an access to the SA_* flags, though I included the signal header. – Papipone Nov 01 '16 at 21:27
  • @Papipone, are you on Linux? You may need to [define a feature macro](http://man7.org/linux/man-pages/man2/sigaction.2.html) like `_POSIX_C_SOURCE`. – pilcrow Nov 01 '16 at 21:34
1

Yes, you can call sigaction inside a signal handler. That's specified by Posix, which (in XBD chapter 2.4.3) "defines a set of functions that shall be async-signal-safe." It then notes that "applications can call them, without restriction, from signal-catching functions. ". sigaction() is in that list.

rici
  • 234,347
  • 28
  • 237
  • 341
1

Just restore the default action in program.

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;
}
Sandeep_black
  • 1,352
  • 17
  • 18