1 /* nanosleep() - Sleep for a number of seconds. Author: Erik van der Kouwe
12 #include <sys/select.h>
15 #define MSEC_PER_SEC 1000
16 #define USEC_PER_MSEC 1000
17 #define NSEC_PER_USEC 1000
19 #define USEC_PER_SEC (USEC_PER_MSEC * MSEC_PER_SEC)
20 #define NSEC_PER_SEC (NSEC_PER_USEC * USEC_PER_SEC)
22 int nanosleep(const struct timespec
*rqtp
, struct timespec
*rmtp
)
24 struct timeval timeout
, timestart
= { 0, 0 }, timeend
;
28 /* check parameters */
32 if (rqtp
->tv_sec
< 0 ||
34 rqtp
->tv_nsec
>= NSEC_PER_SEC
)
37 /* store *rqtp to make sure it is not overwritten */
40 /* keep track of start time if needed */
45 if (gettimeofday(×tart
, NULL
) < 0)
49 /* use select to wait */
50 timeout
.tv_sec
= rqt
.tv_sec
;
51 timeout
.tv_usec
= (rqt
.tv_nsec
+ NSEC_PER_USEC
- 1) / NSEC_PER_USEC
;
52 r
= select(0, NULL
, NULL
, NULL
, &timeout
);
54 /* return remaining time only if requested */
55 /* if select succeeded then we slept all time */
59 /* measure end time; preserve errno */
61 if (gettimeofday(&timeend
, NULL
) < 0)
66 /* compute remaining time */
67 rmtp
->tv_sec
= rqt
.tv_sec
- (timeend
.tv_sec
- timestart
.tv_sec
);
68 rmtp
->tv_nsec
= rqt
.tv_nsec
- (timeend
.tv_usec
- timestart
.tv_usec
) * NSEC_PER_USEC
;
70 /* bring remaining time into canonical form */
71 while (rmtp
->tv_nsec
< 0)
74 rmtp
->tv_nsec
+= NSEC_PER_SEC
;
77 while (rmtp
->tv_nsec
> NSEC_PER_SEC
)
80 rmtp
->tv_nsec
-= NSEC_PER_SEC
;
83 /* remaining time must not be negative */
94 #if defined(__minix) && defined(__weak_alias)
95 __weak_alias(nanosleep
, __nanosleep50
)