| 1 | /* |
| 2 | * clock_nanosleep.c - clock_nanosleep() replacement |
| 3 | */ |
| 4 | |
| 5 | /*********************************************************************** |
| 6 | * Copyright © 2006 Rémi Denis-Courmont. * |
| 7 | * This program is free software; you can redistribute and/or modify * |
| 8 | * it under the terms of the GNU General Public License as published * |
| 9 | * by the Free Software Foundation; version 2 of the license, or (at * |
| 10 | * your option) any later version. * |
| 11 | * * |
| 12 | * This program is distributed in the hope that it will be useful, * |
| 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * |
| 15 | * See the GNU General Public License for more details. * |
| 16 | * * |
| 17 | * You should have received a copy of the GNU General Public License * |
| 18 | * along with this program; if not, you can get it from: * |
| 19 | * http://www.gnu.org/copyleft/gpl.html * |
| 20 | ***********************************************************************/ |
| 21 | |
| 22 | #include <errno.h> // for errno, EINVAL |
| 23 | #include <time.h> // for nanosleep, NULL |
| 24 | |
| 25 | #include "clock_nanosleep.h" |
| 26 | #ifdef MISSING_GETTIME |
| 27 | #include "../clock_gettime/clock_gettime.h" // for clock_gettime |
| 28 | #endif |
| 29 | |
| 30 | int clock_nanosleep(clockid_t id, int flags, const struct timespec *ts, |
| 31 | struct timespec *ots) { |
| 32 | int ret; |
| 33 | |
| 34 | if (id != CLOCK_REALTIME) |
| 35 | return EINVAL; |
| 36 | |
| 37 | if (flags & TIMER_ABSTIME) { |
| 38 | struct timespec mine; |
| 39 | |
| 40 | if (clock_gettime(id, &mine)) |
| 41 | return errno; |
| 42 | |
| 43 | if (mine.tv_sec > ts->tv_sec) |
| 44 | return 0; // behind schedule |
| 45 | |
| 46 | if (mine.tv_nsec > ts->tv_nsec) { |
| 47 | if (mine.tv_sec == ts->tv_sec) |
| 48 | return 0; // behind schedule too |
| 49 | |
| 50 | mine.tv_nsec = 1000000000 + ts->tv_nsec - mine.tv_nsec; |
| 51 | mine.tv_sec++; |
| 52 | } |
| 53 | else |
| 54 | mine.tv_nsec = ts->tv_nsec - mine.tv_nsec; |
| 55 | |
| 56 | mine.tv_sec = ts->tv_sec - mine.tv_sec; |
| 57 | |
| 58 | /* With TIMER_ABSTIME, clock_nanosleep ignores <ots> */ |
| 59 | ret = nanosleep(&mine, NULL); |
| 60 | } |
| 61 | else |
| 62 | ret = nanosleep(ts, ots); |
| 63 | |
| 64 | return ret ? errno : 0; |
| 65 | } |