Search code examples
csignals

Guarantee that signal handler will be called when sigsuspend returns


Suppose that I have the following signal handler set up for SIGALRM:

volatile sigatomic_t alarm_flag;

void alarm_handler(int signum)
{
    (void)signum;
    alarm_flag = 1;
}

Then suppose I've called alarm and then entered a section of code where SIGALRM is blocked but I'd like to synchronize with it. That is, I want to use sigsuspend to wait for the alarm to expire:

sigfillset(&set);
sigdelset(&set, SIGALRM);
sigsuspend(&set);
some_other_command();

Is there any POSIX guarantee that alarm_handler will have been called by the time some_other_command is executed or do I need to do the following?

sigsuspend(&set);
while ( !alarm_flag );
some_other_command();

Solution

  • From the POSIX documentation for sigsuspend():

    If the action is to execute a signal-catching function, then sigsuspend() shall return after the signal-catching function returns, with the signal mask restored to the set that existed prior to the sigsuspend() call.

    So yes, there is a guarantee. If you weren't blocking SIGALARM in the sigsuspend(), at least (and assuming the alarm wasn't handled before calling it, of course).