1 /* Sleep for a given number of seconds. POSIX.1 version.
2 Copyright (C) 1991-2015 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/>. */
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. */
33 __sleep (unsigned int seconds
)
35 /* This is not necessary but some buggy programs depend on it. */
36 if (__glibc_unlikely (seconds
== 0))
39 CANCELLATION_P (THREAD_SELF
);
44 int save_errno
= errno
;
46 const unsigned int max
47 = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1);
48 struct timespec ts
= { 0, 0 };
51 if (sizeof (ts
.tv_sec
) <= sizeof (seconds
))
53 /* Since SECONDS is unsigned assigning the value to .tv_sec can
54 overflow it. In this case we have to wait in steps. */
55 ts
.tv_sec
+= MIN (seconds
, max
);
56 seconds
-= (unsigned int) ts
.tv_sec
;
60 ts
.tv_sec
= (time_t) seconds
;
64 if (__nanosleep (&ts
, &ts
) < 0)
65 /* We were interrupted.
66 Return the number of (whole) seconds we have not yet slept. */
67 return seconds
+ ts
.tv_sec
;
71 __set_errno (save_errno
);
75 weak_alias (__sleep
, sleep
)