- enum { BILLION = 1000000000 };
-
- bool overflow = false;
- double ns;
- struct timespec ts_sleep;
-
- assert (0 <= seconds);
-
- /* Separate whole seconds from nanoseconds.
- Be careful to detect any overflow. */
- ts_sleep.tv_sec = seconds;
- ns = BILLION * (seconds - ts_sleep.tv_sec);
- overflow |= ! (ts_sleep.tv_sec <= seconds && 0 <= ns && ns <= BILLION);
- ts_sleep.tv_nsec = ns;
-
- /* Round up to the next whole number, if necessary, so that we
- always sleep for at least the requested amount of time. Assuming
- the default rounding mode, we don't have to worry about the
- rounding error when computing 'ns' above, since the error won't
- cause 'ns' to drop below an integer boundary. */
- ts_sleep.tv_nsec += (ts_sleep.tv_nsec < ns);
-
- /* Normalize the interval length. nanosleep requires this. */
- if (BILLION <= ts_sleep.tv_nsec)
- {
- time_t t = ts_sleep.tv_sec + 1;
-
- /* Detect integer overflow. */
- overflow |= (t < ts_sleep.tv_sec);
-
- ts_sleep.tv_sec = t;
- ts_sleep.tv_nsec -= BILLION;
- }