doc: mention new timeout short options in NEWS
[coreutils.git] / src / timeout.c
blob5600ce42957dcf117785f6a361ef72ac9c2df352
1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* timeout - Start a command, and kill it if the specified timeout expires
20 We try to behave like a shell starting a single (foreground) job,
21 and will kill the job if we receive the alarm signal we setup.
22 The exit status of the job is returned, or one of these errors:
23 EXIT_TIMEDOUT 124 job timed out
24 EXIT_CANCELED 125 internal error
25 EXIT_CANNOT_INVOKE 126 error executing job
26 EXIT_ENOENT 127 couldn't find job to exec
28 Caveats:
29 If user specifies the KILL (9) signal is to be sent on timeout,
30 the monitor is killed and so exits with 128+9 rather than 124.
32 If you start a command in the background, which reads from the tty
33 and so is immediately sent SIGTTIN to stop, then the timeout
34 process will ignore this so it can timeout the command as expected.
35 This can be seen with 'timeout 10 dd&' for example.
36 However if one brings this group to the foreground with the 'fg'
37 command before the timer expires, the command will remain
38 in the stop state as the shell doesn't send a SIGCONT
39 because the timeout process (group leader) is already running.
40 To get the command running again one can Ctrl-Z, and do fg again.
41 Note one can Ctrl-C the whole job when in this state.
42 I think this could be fixed but I'm not sure the extra
43 complication is justified for this scenario.
45 Written by Pádraig Brady. */
47 #include <config.h>
48 #include <getopt.h>
49 #include <stdio.h>
50 #include <sys/types.h>
51 #include <signal.h>
52 #if HAVE_PRCTL
53 # include <sys/prctl.h>
54 #endif
55 #include <sys/wait.h>
57 #include "system.h"
58 #include "cl-strtod.h"
59 #include "xstrtod.h"
60 #include "sig2str.h"
61 #include "operand2sig.h"
62 #include "quote.h"
64 #if HAVE_SETRLIMIT
65 /* FreeBSD 5.0 at least needs <sys/types.h> and <sys/time.h> included
66 before <sys/resource.h>. Currently "system.h" includes <sys/time.h>. */
67 # include <sys/resource.h>
68 #endif
70 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt. */
71 #ifndef SA_RESTART
72 # define SA_RESTART 0
73 #endif
75 #define PROGRAM_NAME "timeout"
77 #define AUTHORS proper_name_lite ("Padraig Brady", "P\303\241draig Brady")
79 static int timed_out;
80 static int term_signal = SIGTERM; /* same default as kill command. */
81 static pid_t monitored_pid;
82 static double kill_after;
83 static bool foreground; /* whether to use another program group. */
84 static bool preserve_status; /* whether to use a timeout status or not. */
85 static bool verbose; /* whether to diagnose timeouts or not. */
86 static char const *command;
88 static struct option const long_options[] =
90 {"foreground", no_argument, nullptr, 'f'},
91 {"kill-after", required_argument, nullptr, 'k'},
92 {"preserve-status", no_argument, nullptr, 'p'},
93 {"signal", required_argument, nullptr, 's'},
94 {"verbose", no_argument, nullptr, 'v'},
95 {GETOPT_HELP_OPTION_DECL},
96 {GETOPT_VERSION_OPTION_DECL},
97 {nullptr, 0, nullptr, 0}
100 /* Start the timeout after which we'll receive a SIGALRM.
101 Round DURATION up to the next representable value.
102 Treat out-of-range values as if they were maximal,
103 as that's more useful in practice than reporting an error.
104 '0' means don't timeout. */
105 static void
106 settimeout (double duration, bool warn)
109 #if HAVE_TIMER_SETTIME
110 /* timer_settime() provides potentially nanosecond resolution. */
112 struct timespec ts = dtotimespec (duration);
113 struct itimerspec its = {.it_interval = {0}, .it_value = ts};
114 timer_t timerid;
115 if (timer_create (CLOCK_REALTIME, nullptr, &timerid) == 0)
117 if (timer_settime (timerid, 0, &its, nullptr) == 0)
118 return;
119 else
121 if (warn)
122 error (0, errno, _("warning: timer_settime"));
123 timer_delete (timerid);
126 else if (warn && errno != ENOSYS)
127 error (0, errno, _("warning: timer_create"));
129 #elif HAVE_SETITIMER
130 /* setitimer() is more portable (to Darwin for example),
131 but only provides microsecond resolution. */
133 struct timeval tv;
134 struct timespec ts = dtotimespec (duration);
135 tv.tv_sec = ts.tv_sec;
136 tv.tv_usec = (ts.tv_nsec + 999) / 1000;
137 if (tv.tv_usec == 1000 * 1000)
139 if (tv.tv_sec != TYPE_MAXIMUM (time_t))
141 tv.tv_sec++;
142 tv.tv_usec = 0;
144 else
145 tv.tv_usec--;
147 struct itimerval it = {.it_interval = {0}, .it_value = tv };
148 if (setitimer (ITIMER_REAL, &it, nullptr) == 0)
149 return;
150 else
152 if (warn && errno != ENOSYS)
153 error (0, errno, _("warning: setitimer"));
155 #endif
157 /* fallback to single second resolution provided by alarm(). */
159 unsigned int timeint;
160 if (UINT_MAX <= duration)
161 timeint = UINT_MAX;
162 else
164 unsigned int duration_floor = duration;
165 timeint = duration_floor + (duration_floor < duration);
167 alarm (timeint);
170 /* send SIG avoiding the current process. */
172 static int
173 send_sig (pid_t where, int sig)
175 /* If sending to the group, then ignore the signal,
176 so we don't go into a signal loop. Note that this will ignore any of the
177 signals registered in install_cleanup(), that are sent after we
178 propagate the first one, which hopefully won't be an issue. Note this
179 process can be implicitly multithreaded due to some timer_settime()
180 implementations, therefore a signal sent to the group, can be sent
181 multiple times to this process. */
182 if (where == 0)
183 signal (sig, SIG_IGN);
184 return kill (where, sig);
187 /* Signal handler which is required for sigsuspend() to be interrupted
188 whenever SIGCHLD is received. */
189 static void
190 chld (int sig)
195 static void
196 cleanup (int sig)
198 if (sig == SIGALRM)
200 timed_out = 1;
201 sig = term_signal;
203 if (0 < monitored_pid)
205 if (kill_after)
207 int saved_errno = errno; /* settimeout may reset. */
208 /* Start a new timeout after which we'll send SIGKILL. */
209 term_signal = SIGKILL;
210 settimeout (kill_after, false);
211 kill_after = 0; /* Don't let later signals reset kill alarm. */
212 errno = saved_errno;
215 /* Send the signal directly to the monitored child,
216 in case it has itself become group leader,
217 or is not running in a separate group. */
218 if (verbose)
220 char signame[MAX (SIG2STR_MAX, INT_BUFSIZE_BOUND (int))];
221 if (sig2str (sig, signame) != 0)
222 snprintf (signame, sizeof signame, "%d", sig);
223 error (0, 0, _("sending signal %s to command %s"),
224 signame, quote (command));
226 send_sig (monitored_pid, sig);
228 /* The normal case is the job has remained in our
229 newly created process group, so send to all processes in that. */
230 if (!foreground)
232 send_sig (0, sig);
233 if (sig != SIGKILL && sig != SIGCONT)
235 send_sig (monitored_pid, SIGCONT);
236 send_sig (0, SIGCONT);
240 else if (monitored_pid == -1)
241 { /* were in the parent, so let it continue to exit below. */
243 else /* monitored_pid == 0 */
244 { /* parent hasn't forked yet, or child has not exec'd yet. */
245 _exit (128 + sig);
249 void
250 usage (int status)
252 if (status != EXIT_SUCCESS)
253 emit_try_help ();
254 else
256 printf (_("\
257 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
258 or: %s [OPTION]\n"), program_name, program_name);
260 fputs (_("\
261 Start COMMAND, and kill it if still running after DURATION.\n\
262 "), stdout);
264 emit_mandatory_arg_note ();
266 fputs (_("\
267 -f, --foreground\n\
268 when not running timeout directly from a shell prompt,\n\
269 allow COMMAND to read from the TTY and get TTY signals;\n\
270 in this mode, children of COMMAND will not be timed out\n\
271 "), stdout);
272 fputs (_("\
273 -k, --kill-after=DURATION\n\
274 also send a KILL signal if COMMAND is still running\n\
275 this long after the initial signal was sent\n\
276 "), stdout);
277 fputs (_("\
278 -p, --preserve-status\n\
279 exit with the same status as COMMAND,\n\
280 even when the command times out\n\
281 "), stdout);
282 fputs (_("\
283 -s, --signal=SIGNAL\n\
284 specify the signal to be sent on timeout;\n\
285 SIGNAL may be a name like 'HUP' or a number;\n\
286 see 'kill -l' for a list of signals\n\
287 "), stdout);
288 fputs (_("\
289 -v, --verbose diagnose to stderr any signal sent upon timeout\n\
290 "), stdout);
292 fputs (HELP_OPTION_DESCRIPTION, stdout);
293 fputs (VERSION_OPTION_DESCRIPTION, stdout);
295 fputs (_("\n\
296 DURATION is a floating point number with an optional suffix:\n\
297 's' for seconds (the default), 'm' for minutes, 'h' for hours or \
298 'd' for days.\nA duration of 0 disables the associated timeout.\n"), stdout);
300 fputs (_("\n\
301 Upon timeout, send the TERM signal to COMMAND, if no other SIGNAL specified.\n\
302 The TERM signal kills any process that does not block or catch that signal.\n\
303 It may be necessary to use the KILL signal, since this signal can't be caught.\
304 \n"), stdout);
306 fputs (_("\n\
307 Exit status:\n\
308 124 if COMMAND times out, and --preserve-status is not specified\n\
309 125 if the timeout command itself fails\n\
310 126 if COMMAND is found but cannot be invoked\n\
311 127 if COMMAND cannot be found\n\
312 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)\n\
313 - the exit status of COMMAND otherwise\n\
314 "), stdout);
316 emit_ancillary_info (PROGRAM_NAME);
318 exit (status);
321 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
322 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
323 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
324 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
325 and return false. Otherwise return true. */
327 static bool
328 apply_time_suffix (double *x, char suffix_char)
330 int multiplier;
332 switch (suffix_char)
334 case 0:
335 case 's':
336 multiplier = 1;
337 break;
338 case 'm':
339 multiplier = 60;
340 break;
341 case 'h':
342 multiplier = 60 * 60;
343 break;
344 case 'd':
345 multiplier = 60 * 60 * 24;
346 break;
347 default:
348 return false;
351 *x *= multiplier;
353 return true;
356 static double
357 parse_duration (char const *str)
359 double duration;
360 char const *ep;
362 if (! (xstrtod (str, &ep, &duration, cl_strtod) || errno == ERANGE)
363 /* Nonnegative interval. */
364 || ! (0 <= duration)
365 /* No extra chars after the number and an optional s,m,h,d char. */
366 || (*ep && *(ep + 1))
367 /* Check any suffix char and update timeout based on the suffix. */
368 || !apply_time_suffix (&duration, *ep))
370 error (0, 0, _("invalid time interval %s"), quote (str));
371 usage (EXIT_CANCELED);
374 return duration;
377 static void
378 unblock_signal (int sig)
380 sigset_t unblock_set;
381 sigemptyset (&unblock_set);
382 sigaddset (&unblock_set, sig);
383 if (sigprocmask (SIG_UNBLOCK, &unblock_set, nullptr) != 0)
384 error (0, errno, _("warning: sigprocmask"));
387 static void
388 install_sigchld (void)
390 struct sigaction sa;
391 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
392 sa.sa_handler = chld;
393 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
394 more likely to work cleanly. */
396 sigaction (SIGCHLD, &sa, nullptr);
398 /* We inherit the signal mask from our parent process,
399 so ensure SIGCHLD is not blocked. */
400 unblock_signal (SIGCHLD);
403 static void
404 install_cleanup (int sigterm)
406 struct sigaction sa;
407 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
408 sa.sa_handler = cleanup;
409 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
410 more likely to work cleanly. */
412 sigaction (SIGALRM, &sa, nullptr); /* our timeout. */
413 sigaction (SIGINT, &sa, nullptr); /* Ctrl-C at terminal for example. */
414 sigaction (SIGQUIT, &sa, nullptr); /* Ctrl-\ at terminal for example. */
415 sigaction (SIGHUP, &sa, nullptr); /* terminal closed for example. */
416 sigaction (SIGTERM, &sa, nullptr); /* if killed, stop monitored proc. */
417 sigaction (sigterm, &sa, nullptr); /* user specified termination signal. */
420 /* Block all signals which were registered with cleanup() as the signal
421 handler, so we never kill processes after waitpid() returns.
422 Also block SIGCHLD to ensure it doesn't fire between
423 waitpid() polling and sigsuspend() waiting for a signal.
424 Return original mask in OLD_SET. */
425 static void
426 block_cleanup_and_chld (int sigterm, sigset_t *old_set)
428 sigset_t block_set;
429 sigemptyset (&block_set);
431 sigaddset (&block_set, SIGALRM);
432 sigaddset (&block_set, SIGINT);
433 sigaddset (&block_set, SIGQUIT);
434 sigaddset (&block_set, SIGHUP);
435 sigaddset (&block_set, SIGTERM);
436 sigaddset (&block_set, sigterm);
438 sigaddset (&block_set, SIGCHLD);
440 if (sigprocmask (SIG_BLOCK, &block_set, old_set) != 0)
441 error (0, errno, _("warning: sigprocmask"));
444 /* Try to disable core dumps for this process.
445 Return TRUE if successful, FALSE otherwise. */
446 static bool
447 disable_core_dumps (void)
449 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
450 if (prctl (PR_SET_DUMPABLE, 0) == 0)
451 return true;
453 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
454 /* Note this doesn't disable processing by a filter in
455 /proc/sys/kernel/core_pattern on Linux. */
456 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0}) == 0)
457 return true;
459 #else
460 return false;
461 #endif
463 error (0, errno, _("warning: disabling core dumps failed"));
464 return false;
468 main (int argc, char **argv)
470 double timeout;
471 int c;
473 initialize_main (&argc, &argv);
474 set_program_name (argv[0]);
475 setlocale (LC_ALL, "");
476 bindtextdomain (PACKAGE, LOCALEDIR);
477 textdomain (PACKAGE);
479 initialize_exit_failure (EXIT_CANCELED);
480 atexit (close_stdout);
482 while ((c = getopt_long (argc, argv, "+fk:ps:v", long_options, nullptr))
483 != -1)
485 switch (c)
487 case 'f':
488 foreground = true;
489 break;
491 case 'k':
492 kill_after = parse_duration (optarg);
493 break;
495 case 'p':
496 preserve_status = true;
497 break;
499 case 's':
500 term_signal = operand2sig (optarg);
501 if (term_signal == -1)
502 usage (EXIT_CANCELED);
503 break;
505 case 'v':
506 verbose = true;
507 break;
509 case_GETOPT_HELP_CHAR;
511 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
513 default:
514 usage (EXIT_CANCELED);
515 break;
519 if (argc - optind < 2)
520 usage (EXIT_CANCELED);
522 timeout = parse_duration (argv[optind++]);
524 argv += optind;
525 command = argv[0];
527 /* Ensure we're in our own group so all subprocesses can be killed.
528 Note we don't just put the child in a separate group as
529 then we would need to worry about foreground and background groups
530 and propagating signals between them. */
531 if (!foreground)
532 setpgid (0, 0);
534 /* Setup handlers before fork() so that we
535 handle any signals caused by child, without races. */
536 install_cleanup (term_signal);
537 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
538 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
539 install_sigchld (); /* Interrupt sigsuspend() when child exits. */
541 /* We configure timers so that SIGALRM is sent on expiry.
542 Therefore ensure we don't inherit a mask blocking SIGALRM. */
543 unblock_signal (SIGALRM);
545 /* Block signals now, so monitored_pid is deterministic in cleanup(). */
546 sigset_t orig_set;
547 block_cleanup_and_chld (term_signal, &orig_set);
549 monitored_pid = fork ();
550 if (monitored_pid == -1)
552 error (0, errno, _("fork system call failed"));
553 return EXIT_CANCELED;
555 else if (monitored_pid == 0) /* child */
557 /* Restore signal mask for child. */
558 if (sigprocmask (SIG_SETMASK, &orig_set, nullptr) != 0)
560 error (0, errno, _("child failed to reset signal mask"));
561 return EXIT_CANCELED;
564 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
565 signal (SIGTTIN, SIG_DFL);
566 signal (SIGTTOU, SIG_DFL);
568 execvp (argv[0], argv);
570 /* exit like sh, env, nohup, ... */
571 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
572 error (0, errno, _("failed to run command %s"), quote (command));
573 return exit_status;
575 else
577 pid_t wait_result;
578 int status;
580 settimeout (timeout, true);
582 /* Note signals remain blocked in parent here, to ensure
583 we don't cleanup() after waitpid() reaps the child,
584 to avoid sending signals to a possibly different process. */
586 while ((wait_result = waitpid (monitored_pid, &status, WNOHANG)) == 0)
587 sigsuspend (&orig_set); /* Wait with cleanup signals unblocked. */
589 if (wait_result < 0)
591 /* shouldn't happen. */
592 error (0, errno, _("error waiting for command"));
593 status = EXIT_CANCELED;
595 else
597 if (WIFEXITED (status))
598 status = WEXITSTATUS (status);
599 else if (WIFSIGNALED (status))
601 int sig = WTERMSIG (status);
602 if (WCOREDUMP (status))
603 error (0, 0, _("the monitored command dumped core"));
604 if (!timed_out && disable_core_dumps ())
606 /* exit with the signal flag set. */
607 signal (sig, SIG_DFL);
608 unblock_signal (sig);
609 raise (sig);
611 /* Allow users to distinguish if command was forcibly killed.
612 Needed with --foreground where we don't send SIGKILL to
613 the timeout process itself. */
614 if (timed_out && sig == SIGKILL)
615 preserve_status = true;
616 status = sig + 128; /* what sh returns for signaled processes. */
618 else
620 /* shouldn't happen. */
621 error (0, 0, _("unknown status from command (%d)"), status);
622 status = EXIT_FAILURE;
626 if (timed_out && !preserve_status)
627 status = EXIT_TIMEDOUT;
628 return status;