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