__aeabi_ldivmod: fix sign logic
[minix.git] / lib / libc / sys-minix / nanosleep.c
blob5478d9a3b9748ea0ce54f779e3103560abde4a7b
1 /* nanosleep() - Sleep for a number of seconds. Author: Erik van der Kouwe
2 * 25 July 2009
3 */
5 #include <sys/cdefs.h>
6 #include "namespace.h"
7 #include <lib.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <time.h>
12 #include <sys/select.h>
13 #include <sys/time.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;
25 int errno_select, r;
26 struct timespec rqt;
28 /* check parameters */
29 if (!rqtp)
30 return EFAULT;
32 if (rqtp->tv_sec < 0 ||
33 rqtp->tv_nsec < 0 ||
34 rqtp->tv_nsec >= NSEC_PER_SEC)
35 return EINVAL;
37 /* store *rqtp to make sure it is not overwritten */
38 rqt = *rqtp;
40 /* keep track of start time if needed */
41 if (rmtp)
43 rmtp->tv_sec = 0;
44 rmtp->tv_nsec = 0;
45 if (gettimeofday(&timestart, NULL) < 0)
46 return -1;
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 */
56 if (!rmtp || r >= 0)
57 return r;
59 /* measure end time; preserve errno */
60 errno_select = errno;
61 if (gettimeofday(&timeend, NULL) < 0)
62 return -1;
64 errno = errno_select;
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)
73 rmtp->tv_sec -= 1;
74 rmtp->tv_nsec += NSEC_PER_SEC;
77 while (rmtp->tv_nsec > NSEC_PER_SEC)
79 rmtp->tv_sec += 1;
80 rmtp->tv_nsec -= NSEC_PER_SEC;
83 /* remaining time must not be negative */
84 if (rmtp->tv_sec < 0)
86 rmtp->tv_sec = 0;
87 rmtp->tv_nsec = 0;
90 return r;
94 #if defined(__minix) && defined(__weak_alias)
95 __weak_alias(nanosleep, __nanosleep50)
96 #endif