1 | /* Sleep for a given number of seconds. POSIX.1 version. |
2 | Copyright (C) 1991-2021 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 | <https://www.gnu.org/licenses/>. */ |
18 | |
19 | #include <time.h> |
20 | #include <unistd.h> |
21 | #include <errno.h> |
22 | #include <sys/param.h> |
23 | |
24 | |
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) |
34 | { |
35 | int save_errno = errno; |
36 | |
37 | const unsigned int max |
38 | = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1); |
39 | struct timespec ts = { 0, 0 }; |
40 | do |
41 | { |
42 | if (sizeof (ts.tv_sec) <= sizeof (seconds)) |
43 | { |
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; |
48 | } |
49 | else |
50 | { |
51 | ts.tv_sec = (time_t) seconds; |
52 | seconds = 0; |
53 | } |
54 | |
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; |
59 | } |
60 | while (seconds > 0); |
61 | |
62 | __set_errno (save_errno); |
63 | |
64 | return 0; |
65 | } |
66 | weak_alias (__sleep, sleep) |
67 | |