Debian Codegraph @

listings/chapter-8/better_sleep.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <errno.h>
8 #include <time.h>
9
10 int better_sleep (double sleep_time)
11 {
12 struct timespec tv;
13 /* Construct the timespec from the number of whole seconds... */
14 tv.tv_sec = (time_t) sleep_time;
15 /* ... and the remainder in nanoseconds. */
16 tv.tv_nsec = (long) ((sleep_time - tv.tv_sec) * 1e+9);
17
18 while (1)
19 {
20 /* Sleep for the time specified in tv. If interrupted by a
21 signal, place the remaining time left to sleep back into tv. */
22 int rval = nanosleep (&tv, &tv);
23 if (rval == 0)
24 /* Completed the entire sleep time; all done. */
25 return 0;
26 else if (errno == EINTR)
27 /* Interruped by a signal. Try again. */
28 continue;
29 else
30 /* Some other error; bail out. */
31 return rval;
32 }
33 return 0;
34 }