linux ttyname and ttyname_r: do not return wrong results
[glibc.git] / sysdeps / posix / sleep.c
blobb3162baab16b08bcaf5376f7742b345c1824984a
1 /* Sleep for a given number of seconds. POSIX.1 version.
2 Copyright (C) 1991-2017 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 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.
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.
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/>. */
19 #include <time.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <sys/param.h>
25 /* Make the process sleep for SECONDS seconds, or until a signal arrives
26 and is not ignored. The function returns the number of seconds less
27 than SECONDS which it actually slept (zero if it slept the full time).
28 If a signal handler does a `longjmp' or modifies the handling of the
29 SIGALRM signal while inside `sleep' call, the handling of the SIGALRM
30 signal afterwards is undefined. There is no return value to indicate
31 error, but if `sleep' returns SECONDS, it probably didn't work. */
32 unsigned int
33 __sleep (unsigned int seconds)
35 int save_errno = errno;
37 const unsigned int max
38 = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1);
39 struct timespec ts = { 0, 0 };
42 if (sizeof (ts.tv_sec) <= sizeof (seconds))
44 /* Since SECONDS is unsigned assigning the value to .tv_sec can
45 overflow it. In this case we have to wait in steps. */
46 ts.tv_sec += MIN (seconds, max);
47 seconds -= (unsigned int) ts.tv_sec;
49 else
51 ts.tv_sec = (time_t) seconds;
52 seconds = 0;
55 if (__nanosleep (&ts, &ts) < 0)
56 /* We were interrupted.
57 Return the number of (whole) seconds we have not yet slept. */
58 return seconds + ts.tv_sec;
60 while (seconds > 0);
62 __set_errno (save_errno);
64 return 0;
66 weak_alias (__sleep, sleep)