]> git.saurik.com Git - apple/libc.git/blob - gen/nanosleep.c
717f30cd44a2095ab307ff06c20b0041c92e28f2
[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 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #include <errno.h>
25 #include <sys/time.h>
26 #include <mach/message.h>
27 #include <mach/mach_error.h>
28 #include <mach/mach_syscalls.h>
29 #include <mach/clock.h>
30 #include <mach/clock_types.h>
31 #include <stdio.h>
32
33 extern mach_port_t clock_port;
34
35 int
36 nanosleep(const struct timespec *requested_time, struct timespec *remaining_time) {
37 kern_return_t ret;
38 mach_timespec_t remain;
39 mach_timespec_t current;
40
41 if ((requested_time == NULL) || (requested_time->tv_sec < 0) || (requested_time->tv_nsec > NSEC_PER_SEC)) {
42 errno = EINVAL;
43 return -1;
44 }
45
46 ret = clock_get_time(clock_port, &current);
47 if (ret != KERN_SUCCESS) {
48 fprintf(stderr, "clock_get_time() failed: %s\n", mach_error_string(ret));
49 return -1;
50 }
51 /* This depends on the layout of a mach_timespec_t and timespec_t being equivalent */
52 ret = clock_sleep_trap(clock_port, TIME_RELATIVE, requested_time->tv_sec, requested_time->tv_nsec, &remain);
53 if (ret != KERN_SUCCESS) {
54 if (ret == KERN_ABORTED) {
55 errno = EINTR;
56 if (remaining_time != NULL) {
57 ret = clock_get_time(clock_port, &remain);
58 if (ret != KERN_SUCCESS) {
59 fprintf(stderr, "clock_get_time() failed: %s\n", mach_error_string(ret));
60 return -1;
61 }
62 ADD_MACH_TIMESPEC(&current, requested_time);
63 SUB_MACH_TIMESPEC(&current, &remain);
64 remaining_time->tv_sec = current.tv_sec;
65 remaining_time->tv_nsec = current.tv_nsec;
66 }
67 } else {
68 errno = EINVAL;
69 }
70 return -1;
71 }
72 return 0;
73 }