Timers and Sleeping 491
request = remain; /* Next sleep is with remaining time */
}
printf("Sleep complete\n");
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––timers/t_nanosleep.c
23.5 POSIX Clocks............................................................................................................
POSIX clocks (originally defined in POSIX.1b) provide an API for accessing clocks
that measure time with nanosecond precision. Nanosecond time values are repre-
sented using the same timespec structure as is used by nanosleep() (Section 23.4.2).
On Linux, programs using this API must be compiled with the –lrt option, in
order to link against the librt (realtime) library.
The main system calls in the POSIX clocks API are clock_gettime(), which
retrieves the current value of a clock; clock_getres(), which returns the resolution of
a clock; and clock_settime(), which updates a clock.
23.5.1 Retrieving the Value of a Clock: clock_gettime()........................................
The clock_gettime() system call returns the time according to the clock specified in
clockid.
The time value is returned in the timespec structure pointed to by tp. Although the
timespec structure affords nanosecond precision, the granularity of the time value
returned by clock_gettime() may be coarser than this. The clock_getres() system call
returns a pointer to a timespec structure containing the resolution of the clock spec-
ified in clockid.
The clockid_t data type is a type specified by SUSv3 for representing a clock
identifier. The first column of Table 23-1 lists the values that can be specified for
clockid.
#define _POSIX_C_SOURCE 199309
#include <time.h>
int clock_gettime(clockid_t clockid, struct timespec *tp);
int clock_getres(clockid_t clockid, struct timespec *res);
Both return 0 on success, or –1 on error
Table 23-1: POSIX.1b clock types
Clock ID Description
CLOCK_REALTIME Settable system-wide real-time clock
CLOCK_MONOTONIC Nonsettable monotonic clock
CLOCK_PROCESS_CPUTIME_ID Per-process CPU-time clock (since Linux 2.6.12)
CLOCK_THREAD_CPUTIME_ID Per-thread CPU-time clock (since Linux 2.6.12)