timers/t_nanosleep.cThis is timers/t_nanosleep.c (Listing 23-3, page 490), an example from the book, The Linux Programming Interface. The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3. This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below. In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.
|
/* t_nanosleep.c Demonstrate the use of nanosleep() to sleep for an interval specified in nanoseconds. See also t_clock_nanosleep.c. */ #define _POSIX_C_SOURCE 199309 #include <sys/time.h> #include <time.h> #include <signal.h> #include "tlpi_hdr.h"
static void sigintHandler(int sig) { return; /* Just interrupt nanosleep() */ }
int main(int argc, char *argv[]) { struct timeval start, finish; struct timespec request, remain; struct sigaction sa; int s; if (argc != 3 || strcmp(argv[1], "--help") == 0) usageErr("%s secs nanosecs\n", argv[0]); request.tv_sec = getLong(argv[1], 0, "secs"); request.tv_nsec = getLong(argv[2], 0, "nanosecs"); /* Allow SIGINT handler to interrupt nanosleep() */ sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = sigintHandler; if (sigaction(SIGINT, &sa, NULL) == -1) errExit("sigaction"); if (gettimeofday(&start, NULL) == -1) errExit("gettimeofday"); for (;;) { s = nanosleep(&request, &remain); if (s == -1 && errno != EINTR) errExit("nanosleep"); if (gettimeofday(&finish, NULL) == -1) errExit("gettimeofday"); printf("Slept for: %9.6f secs\n", finish.tv_sec - start.tv_sec + (finish.tv_usec - start.tv_usec) / 1000000.0); if (s == 0) break; /* nanosleep() completed */ printf("Remaining: %2ld.%09ld\n", (long) remain.tv_sec, remain.tv_nsec); request = remain; /* Next sleep is with remaining time */ } printf("Sleep complete\n"); exit(EXIT_SUCCESS); }
Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.