25.7.4 Blocking to Test for Delivery of a Signal

Now for a simple example. Suppose you establish a handler for SIGALRM signals that sets a flag whenever a signal arrives, and your main program checks this flag from time to time and then resets it. You can prevent additional SIGALRM signals from arriving in the meantime by wrapping the critical part of the code with calls to sigprocmask, like this:

/* This variable is set by the SIGALRM signal handler. */
volatile sig_atomic_t flag = 0;

int
main (void)
{
  sigset_t block_alarm;

  …

  /* Initialize the signal mask. */
  sigemptyset (&block_alarm);
  sigaddset (&block_alarm, SIGALRM);

  while (1)
    {
      /* Check if a signal has arrived; if so, reset the flag. */
      sigprocmask (SIG_BLOCK, &block_alarm, NULL);
      if (flag)
        {
          actions-if-not-arrived
          flag = 0;
        }
      sigprocmask (SIG_UNBLOCK, &block_alarm, NULL);

      …
    }
}