The function sleep
gives a simple way to make the program wait
for short periods of time. If your program doesn't use signals (except
to terminate), then you can expect sleep
to wait reliably for
the specified amount of time. Otherwise, sleep
can return sooner
if a signal arrives; if you want to wait for a given period regardless
of signals, use select
(see section Waiting for Input or Output) and don't
specify any descriptors to wait for.
sleep
function waits for seconds or until a signal
is delivered, whichever happens first.
If sleep
function returns because the requested time has
elapsed, it returns a value of zero. If it returns because of delivery
of a signal, its return value is the remaining time in the sleep period.
The sleep
function is declared in `unistd.h'.
Resist the temptation to implement a sleep for a fixed amount of time by
using the return value of sleep
, when nonzero, to call
sleep
again. This will work with a certain amount of accuracy as
long as signals arrive infrequently. But each signal can cause the
eventual wakeup time to be off by an additional second or so. Suppose a
few signals happen to arrive in rapid succession by bad luck--there is
no limit on how much this could shorten or lengthen the wait.
Instead, compute the time at which the program should stop waiting, and
keep trying to wait until that time. This won't be off by more than a
second. With just a little more work, you can use select
and
make the waiting period quite accurate. (Of course, heavy system load
can cause unavoidable additional delays--unless the machine is
dedicated to one application, there is no way you can avoid this.)
On some systems, sleep
can do strange things if your program uses
SIGALRM
explicitly. Even if SIGALRM
signals are being
ignored or blocked when sleep
is called, sleep
might
return prematurely on delivery of a SIGALRM
signal. If you have
established a handler for SIGALRM
signals and a SIGALRM
signal is delivered while the process is sleeping, the action taken
might be just to cause sleep
to return instead of invoking your
handler. And, if sleep
is interrupted by delivery of a signal
whose handler requests an alarm or alters the handling of SIGALRM
,
this handler and sleep
will interfere.
On the GNU system, it is safe to use sleep
and SIGALRM
in
the same program, because sleep
does not work by means of
SIGALRM
.
Go to the first, previous, next, last section, table of contents.