lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* nanosleep -- sleep for a period specified with a struct timespec |
| 2 | Copyright (C) 2002-2015 Free Software Foundation, Inc. |
| 3 | This file is part of the GNU C Library. |
| 4 | |
| 5 | The GNU C Library is free software; you can redistribute it and/or |
| 6 | modify it under the terms of the GNU Lesser General Public |
| 7 | License as published by the Free Software Foundation; either |
| 8 | version 2.1 of the License, or (at your option) any later version. |
| 9 | |
| 10 | The GNU C Library is distributed in the hope that it will be useful, |
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | Lesser General Public License for more details. |
| 14 | |
| 15 | You should have received a copy of the GNU Lesser General Public |
| 16 | License along with the GNU C Library; if not, see |
| 17 | <http://www.gnu.org/licenses/>. */ |
| 18 | |
| 19 | #include <errno.h> |
| 20 | #include <mach.h> |
| 21 | #include <sys/time.h> |
| 22 | #include <unistd.h> |
| 23 | |
| 24 | int |
| 25 | __nanosleep (const struct timespec *requested_time, |
| 26 | struct timespec *remaining) |
| 27 | { |
| 28 | mach_port_t recv; |
| 29 | struct timeval before, after; |
| 30 | |
| 31 | if (requested_time->tv_sec < 0 |
| 32 | || requested_time->tv_nsec < 0 |
| 33 | || requested_time->tv_nsec >= 1000000000) |
| 34 | { |
| 35 | errno = EINVAL; |
| 36 | return -1; |
| 37 | } |
| 38 | |
| 39 | const mach_msg_timeout_t ms |
| 40 | = requested_time->tv_sec * 1000 |
| 41 | + (requested_time->tv_nsec + 999999) / 1000000; |
| 42 | |
| 43 | recv = __mach_reply_port (); |
| 44 | |
| 45 | if (remaining && __gettimeofday (&before, NULL) < 0) |
| 46 | return -1; |
| 47 | error_t err = __mach_msg (NULL, MACH_RCV_MSG|MACH_RCV_TIMEOUT|MACH_RCV_INTERRUPT, |
| 48 | 0, 0, recv, ms, MACH_PORT_NULL); |
| 49 | __mach_port_destroy (mach_task_self (), recv); |
| 50 | if (err == EMACH_RCV_INTERRUPTED) |
| 51 | { |
| 52 | if (remaining && __gettimeofday (&after, NULL) >= 0) |
| 53 | { |
| 54 | struct timeval req_time, elapsed, rem; |
| 55 | TIMESPEC_TO_TIMEVAL (&req_time, requested_time); |
| 56 | timersub (&after, &before, &elapsed); |
| 57 | timersub (&req_time, &elapsed, &rem); |
| 58 | TIMEVAL_TO_TIMESPEC (&rem, remaining); |
| 59 | } |
| 60 | |
| 61 | errno = EINTR; |
| 62 | return -1; |
| 63 | } |
| 64 | |
| 65 | return 0; |
| 66 | } |
| 67 | libc_hidden_def (__nanosleep) |
| 68 | weak_alias (__nanosleep, nanosleep) |