Adjusted.
[glibc.git] / sysdeps / unix / clock_nanosleep.c
blob0170188f067e4dcd70c36b133b02aaf7f12ec1e1
1 /* High-resolution sleep with the specified clock.
2 Copyright (C) 2000, 2001 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include <assert.h>
21 #include <errno.h>
22 #include <time.h>
25 #ifndef CLOCK_P
26 # define CLOCK_P(clock) 0
27 #endif
30 /* This implementation assumes that these is only a `nanosleep' system
31 call. So we have to remap all other activities. */
32 int
33 clock_nanosleep (clockid_t clock_id, int flags, const struct timespec *req,
34 struct timespec *rem)
36 struct timespec now;
38 if (__builtin_expect (req->tv_nsec, 0) < 0
39 || __builtin_expect (req->tv_nsec, 0) >= 1000000000)
40 return EINVAL;
42 /* If we got an absolute time, remap it. */
43 if (flags == TIMER_ABSTIME)
45 long int nsec;
46 long int sec;
48 /* Make sure we use safe data types. */
49 assert (sizeof (sec) >= sizeof (now.tv_sec));
51 /* Get the current time for this clock. */
52 if (__builtin_expect (clock_gettime (clock_id, &now), 0) != 0)
53 return errno;
55 /* Compute the difference. */
56 nsec = req->tv_nsec - now.tv_nsec;
57 sec = req->tv_sec - now.tv_sec - (nsec < 0);
58 if (sec < 0)
59 /* The time has already elapsed. */
60 return 0;
62 now.tv_sec = sec;
63 now.tv_nsec = nsec + (nsec < 0 ? 1000000000 : 0);
65 /* From now on this is our time. */
66 req = &now;
68 /* Make sure we are not modifying the struct pointed to by REM. */
69 rem = NULL;
71 else if (__builtin_expect (flags, 0) != 0)
72 return EINVAL;
73 else if (clock_id != CLOCK_REALTIME)
75 /* Make sure the clock ID is correct. */
76 if (__builtin_expect (! CLOCK_P (clock_id), 0))
77 return EINVAL;
80 return __builtin_expect (nanosleep (req, rem), 0) ? errno : 0;