sleep, nanosleep, and clock_nanosleep Functions
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
This function causes the calling process to be suspended until either
1.The amount of wall clock time specified by seconds has elapsed.
2.A signal is caught by the process and the signal handler returns.
As with an alarm signal, the actual return may occur at a time later than requested because of other system activity.
FreeBSD 8.0, Linux 3.2.0, Mac OS X 10.6.8, and Solaris 10 implement sleep using the nanosleep function, which allows the implementation to be independent of signals and the alarm timer. For portability, you shouldn’t make any assumptions about the implementation of sleep, but if you have any intentions of mixing calls to sleep with any other timing functions, you need to be aware of possible interactions.
#include "apue.h"
static void sig_alrm(int signo)
{
}
unsigned int sleep(unsigned int seconds)
{
struct sigaction newact,oldact;
sigset_t newmask, oldmask, suspmask;
unsigned int unslept;
newact.sa_handler=sig_alrm;
sigemptyset(&newact.sa_mask);
sigaction(SIGALRM,&newact,&oldact);
sigemptyset(&newmask);
sigaddset(&newmask,SIGALRM);
sigprocmask(SIG_BLOCK,&newmask,&oldmask);
alarm(seconds);
suspmask=oldmask;
sigdelset(&suspmask,SIGALRM);
sigsuspend(&suspmask);
unsplet=alarm(0);
sigaction(SIGALRM,&oldact,NULL);
sigprocmask(SIG_SETMASK,&oldmask,NULL);
return unsplet;
}
Reliable implementation of sleep
The nanosleep function is similar to the sleep function, but provides nanosecond-level granularity.
#include <time.h>
int nanosleep(consts struct timespec *reqtp, struct timespec *remtp);
If the system doesn’t support nanosecond granularity, the requested time is rounded up. Because the nanosleep function doesn’t involve the generation of any signals, we can use it without worrying about interactions with other functions.
The nanosleep function used to belong to the Timers option in the Single UNIX Specification, but was moved to the base in SUSv4.
With the introduction of multiple system clocks (recall Section 6.10), we need a way to suspend the calling thread using a delay time relative to a particular clock. The clock_nanosleep function provides us with this capability
#include <time.h>
int clock_nanosleep(clockid_t clock_id,int flags, const struct timespec *reqtp, struct timespec *remtp);
Note that except for error returns, the call
clock_nanosleep(CLOCK_REALTIME, 0, reqtp, remtp);
has the same effect as the call
nanosleep(reqtp, remtp);
The problem with using a relative sleep is that some applications require precision with how long they sleep, and a relative sleep time can lead to sleeping longer than desired.
In older versions of the Single UNIX Specification, the clock_nanosleep function belonged to the Clock Selection option. In SUSv4, it was moved to the base.