Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.19 sleep,nanosleep,andclock_nanosleepFunctions 373


10.19 sleep, nanosleep,and clock_nanosleep Functions


We’ve used thesleepfunction in numerous examples throughout the text, and we
showed two flawed implementations of it in Figures 10.7 and 10.8.
#include <unistd.h>
unsigned int sleep(unsigned intseconds);
Returns: 0 or number of unslept seconds
This function causes the calling process to be suspended until either


  1. The amount of wall clock time specified bysecondshas elapsed.

  2. A signal is caught by the process and the signal handler returns.


As with analarmsignal, the actual return may occur at a time later than requested
because of other system activity.
In case 1, the return value is 0. Whensleepreturns early because of some signal
being caught (case 2), the return value is the number of unslept seconds (the requested
time minus the actual time slept).
Althoughsleepcan be implemented with thealarmfunction (Section 10.10), this
isn’t required. Ifalarmis used, however,therecan be interactions between the two
functions. The POSIX.1 standardleaves all these interactions unspecified. For example,
if we do analarm(10)and 3 wall clock seconds later do asleep(5),what happens?
Thesleepwill return in 5 seconds (assuming that some other signal isn’t caught in the
interim), but will anotherSIGALRMbe generated 2 seconds later? These details depend
on the implementation.

FreeBSD 8.0, Linux 3.2.0, Mac OS X 10.6.8, and Solaris 10 implementsleepusing the
nanosleepfunction, which allows the implementation to be independent of signals and the
alarm timer.For portability,you shouldn’t make any assumptions about the implementation
ofsleep,but if you have any intentions of mixing calls tosleepwith any other timing
functions, you need to be aware of possible interactions.

Example


Figure10.29 shows an implementation of the POSIX.1sleepfunction. This function is
amodification of Figure10.7, which handles signals reliably,avoiding the race condition
in the earlier implementation. We still do not handle any interactions with previously
set alarms. (As we mentioned, these interactions areexplicitly undefined by POSIX.1.)
#include "apue.h"
static void
sig_alrm(int signo)
{
/* nothing to do, just returning wakes up sigsuspend() */
}
unsigned int
Free download pdf