Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.10 alarmandpauseFunctions 339


The only timepausereturns is if a signal handler is executed and that handler returns.
In that case,pausereturns−1witherrnoset toEINTR.

Example


Usingalarmandpause, we can put a process to sleep for a specified amount of time.
Thesleep1function in Figure10.7 appears to do this (but it has problems, as we shall
see shortly).
#include <signal.h>
#include <unistd.h>
static void
sig_alrm(int signo)
{
/* nothing to do, just return to wake up the pause */
}
unsigned int
sleep1(unsigned int seconds)
{
if (signal(SIGALRM, sig_alrm) == SIG_ERR)
return(seconds);
alarm(seconds); /* start the timer */
pause(); /* next caught signal wakes us up */
return(alarm(0)); /* turn off timer, return unslept time */
}

Figure 10.7 Simple, incomplete implementation ofsleep

This function looks like thesleepfunction, which we describe in Section 10.19, but this
simple implementation has three problems.


  1. If the caller already has an alarm set, that alarm is erased by the first call to
    alarm.Wecan correct this by looking atalarm’s return value. If the number
    of seconds until some previously set alarm is less than the argument, then we
    should wait only until the existing alarm expires. If the previously set alarm
    will go offafter ours, then beforereturning we should reset this alarm to occur
    at its designated time in the future.

  2. Wehave modified the disposition forSIGALRM.Ifwe’rewriting a function for
    others to call, we should save the disposition when our function is called and
    restore it when we’redone. Wecan correct this by saving the return value from
    signaland resetting the disposition beforeour function returns.

  3. There is a race condition between the first call toalarmand the call topause.
    On a busy system, it’s possible for the alarm to go offand the signal handler to
    be called before we callpause.Ifthat happens, the caller is suspended forever
    in the call topause(assuming that some other signal isn’t caught).

Free download pdf