]> git.saurik.com Git - apple/libc.git/blob - gen/nanosleep.c
Libc-339.tar.gz
[apple/libc.git] / gen / nanosleep.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
7 *
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 */
25
26 #include <errno.h>
27 #include <sys/time.h>
28 #include <mach/mach_error.h>
29 #include <mach/mach_time.h>
30 #include <stdio.h>
31
32 int
33 nanosleep(const struct timespec *requested_time, struct timespec *remaining_time) {
34 kern_return_t ret;
35 mach_timespec_t remain;
36 mach_timespec_t current;
37 uint64_t end;
38 static double ratio = 0.0, rratio;
39
40 if ((requested_time == NULL) || (requested_time->tv_sec < 0) || (requested_time->tv_nsec > NSEC_PER_SEC)) {
41 errno = EINVAL;
42 return -1;
43 }
44
45 if (ratio == 0.0) {
46 struct mach_timebase_info info;
47 ret = mach_timebase_info(&info);
48 if (ret != KERN_SUCCESS) {
49 fprintf(stderr, "mach_timebase_info() failed: %s\n", mach_error_string(ret));
50 errno = EAGAIN;
51 return -1;
52 }
53 ratio = (double)info.numer / ((double)info.denom * NSEC_PER_SEC);
54 rratio = (double)info.denom / (double)info.numer;
55 }
56
57 /* use rratio to avoid division */
58 end = mach_absolute_time() + (uint64_t)(((double)requested_time->tv_sec * NSEC_PER_SEC + (double)requested_time->tv_nsec) * rratio);
59 ret = mach_wait_until(end);
60 if (ret != KERN_SUCCESS) {
61 if (ret == KERN_ABORTED) {
62 errno = EINTR;
63 if (remaining_time != NULL) {
64 uint64_t now = mach_absolute_time();
65 double delta;
66 if (now > end)
67 now = end;
68 delta = (end - now) * ratio;
69 remaining_time->tv_sec = delta;
70 remaining_time->tv_nsec = NSEC_PER_SEC * (delta - remaining_time->tv_sec);
71 }
72 } else {
73 errno = EINVAL;
74 }
75 return -1;
76 }
77 return 0;
78 }