25.8.2 Problems with pause

The simplicity of pause can conceal serious timing errors that can make a program hang mysteriously.

It is safe to use pause if the real work of your program is done by the signal handlers themselves, and the “main program” does nothing but call pause. Each time a signal is delivered, the handler will do the next batch of work that is to be done, and then return, so that the main loop of the program can call pause again.

You can’t safely use pause to wait until one more signal arrives, and then resume real work. Even if you arrange for the signal handler to cooperate by setting a flag, you still can’t use pause reliably. Here is an example of this problem:

/* usr_interrupt is set by the signal handler.  */
if (!usr_interrupt)
  pause ();

/* Do work once the signal arrives.  */
...

This has a bug: the signal could arrive after the variable usr_interrupt is checked, but before the call to pause. If no further signals arrive, the process would never wake up again.

You can put an upper limit on the excess waiting by using sleep in a loop, instead of using pause. (See Sleeping, for more about sleep.) Here is what this looks like:

/* usr_interrupt is set by the signal handler.
while (!usr_interrupt)
  sleep (1);

/* Do work once the signal arrives.  */
...

For some purposes, that is good enough. But with a little more complexity, you can wait reliably until a particular signal handler is run, using sigsuspend.