1 /* xnanosleep.c -- a more convenient interface to nanosleep
3 Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 /* Mostly written (for sleep.c) by Paul Eggert.
20 Factored out (creating this file) by Jim Meyering. */
24 #include "xnanosleep.h"
31 #include <sys/types.h>
38 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
41 /* Sleep until the time (call it WAKE_UP_TIME) specified as
42 SECONDS seconds after the time this function is called.
43 SECONDS must be non-negative. If SECONDS is so large that
44 it is not representable as a `struct timespec', then use
45 the maximum value for that interval. Return -1 on failure
46 (setting errno), 0 on success. */
49 xnanosleep (double seconds)
51 enum { BILLION = 1000000000 };
53 bool overflow = false;
55 struct timespec ts_sleep;
57 assert (0 <= seconds);
59 /* Separate whole seconds from nanoseconds.
60 Be careful to detect any overflow. */
61 ts_sleep.tv_sec = seconds;
62 ns = BILLION * (seconds - ts_sleep.tv_sec);
63 overflow |= ! (ts_sleep.tv_sec <= seconds && 0 <= ns && ns <= BILLION);
64 ts_sleep.tv_nsec = ns;
66 /* Round up to the next whole number, if necessary, so that we
67 always sleep for at least the requested amount of time. Assuming
68 the default rounding mode, we don't have to worry about the
69 rounding error when computing 'ns' above, since the error won't
70 cause 'ns' to drop below an integer boundary. */
71 ts_sleep.tv_nsec += (ts_sleep.tv_nsec < ns);
73 /* Normalize the interval length. nanosleep requires this. */
74 if (BILLION <= ts_sleep.tv_nsec)
76 time_t t = ts_sleep.tv_sec + 1;
78 /* Detect integer overflow. */
79 overflow |= (t < ts_sleep.tv_sec);
82 ts_sleep.tv_nsec -= BILLION;
89 ts_sleep.tv_sec = TIME_T_MAX;
90 ts_sleep.tv_nsec = BILLION - 1;
93 /* Linux-2.6.8.1's nanosleep returns -1, but doesn't set errno
94 when resumed after being suspended. Earlier versions would
95 set errno to EINTR. nanosleep from linux-2.6.10, as well as
96 implementations by (all?) other vendors, doesn't return -1
97 in that case; either it continues sleeping (if time remains)
98 or it returns zero (if the wake-up time has passed). */
100 if (nanosleep (&ts_sleep, NULL) == 0)
102 if (errno != EINTR && errno != 0)