wc: increase I/O size from 16 KiB to 256KiB
[coreutils.git] / src / timeout.c
blobc102aff858b7075465067424261d1e39ec71ddff
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 /* for long options with no corresponding short option, use enum */
89 enum
91 FOREGROUND_OPTION = CHAR_MAX + 1,
92 PRESERVE_STATUS_OPTION
95 static struct option const long_options[] =
97 {"kill-after", required_argument, nullptr, 'k'},
98 {"signal", required_argument, nullptr, 's'},
99 {"verbose", no_argument, nullptr, 'v'},
100 {"foreground", no_argument, nullptr, FOREGROUND_OPTION},
101 {"preserve-status", no_argument, nullptr, PRESERVE_STATUS_OPTION},
102 {GETOPT_HELP_OPTION_DECL},
103 {GETOPT_VERSION_OPTION_DECL},
104 {nullptr, 0, nullptr, 0}
107 /* Start the timeout after which we'll receive a SIGALRM.
108 Round DURATION up to the next representable value.
109 Treat out-of-range values as if they were maximal,
110 as that's more useful in practice than reporting an error.
111 '0' means don't timeout. */
112 static void
113 settimeout (double duration, bool warn)
116 #if HAVE_TIMER_SETTIME
117 /* timer_settime() provides potentially nanosecond resolution. */
119 struct timespec ts = dtotimespec (duration);
120 struct itimerspec its = {.it_interval = {0}, .it_value = ts};
121 timer_t timerid;
122 if (timer_create (CLOCK_REALTIME, nullptr, &timerid) == 0)
124 if (timer_settime (timerid, 0, &its, nullptr) == 0)
125 return;
126 else
128 if (warn)
129 error (0, errno, _("warning: timer_settime"));
130 timer_delete (timerid);
133 else if (warn && errno != ENOSYS)
134 error (0, errno, _("warning: timer_create"));
136 #elif HAVE_SETITIMER
137 /* setitimer() is more portable (to Darwin for example),
138 but only provides microsecond resolution. */
140 struct timeval tv;
141 struct timespec ts = dtotimespec (duration);
142 tv.tv_sec = ts.tv_sec;
143 tv.tv_usec = (ts.tv_nsec + 999) / 1000;
144 if (tv.tv_usec == 1000 * 1000)
146 if (tv.tv_sec != TYPE_MAXIMUM (time_t))
148 tv.tv_sec++;
149 tv.tv_usec = 0;
151 else
152 tv.tv_usec--;
154 struct itimerval it = {.it_interval = {0}, .it_value = tv };
155 if (setitimer (ITIMER_REAL, &it, nullptr) == 0)
156 return;
157 else
159 if (warn && errno != ENOSYS)
160 error (0, errno, _("warning: setitimer"));
162 #endif
164 /* fallback to single second resolution provided by alarm(). */
166 unsigned int timeint;
167 if (UINT_MAX <= duration)
168 timeint = UINT_MAX;
169 else
171 unsigned int duration_floor = duration;
172 timeint = duration_floor + (duration_floor < duration);
174 alarm (timeint);
177 /* send SIG avoiding the current process. */
179 static int
180 send_sig (pid_t where, int sig)
182 /* If sending to the group, then ignore the signal,
183 so we don't go into a signal loop. Note that this will ignore any of the
184 signals registered in install_cleanup(), that are sent after we
185 propagate the first one, which hopefully won't be an issue. Note this
186 process can be implicitly multithreaded due to some timer_settime()
187 implementations, therefore a signal sent to the group, can be sent
188 multiple times to this process. */
189 if (where == 0)
190 signal (sig, SIG_IGN);
191 return kill (where, sig);
194 /* Signal handler which is required for sigsuspend() to be interrupted
195 whenever SIGCHLD is received. */
196 static void
197 chld (int sig)
202 static void
203 cleanup (int sig)
205 if (sig == SIGALRM)
207 timed_out = 1;
208 sig = term_signal;
210 if (0 < monitored_pid)
212 if (kill_after)
214 int saved_errno = errno; /* settimeout may reset. */
215 /* Start a new timeout after which we'll send SIGKILL. */
216 term_signal = SIGKILL;
217 settimeout (kill_after, false);
218 kill_after = 0; /* Don't let later signals reset kill alarm. */
219 errno = saved_errno;
222 /* Send the signal directly to the monitored child,
223 in case it has itself become group leader,
224 or is not running in a separate group. */
225 if (verbose)
227 char signame[MAX (SIG2STR_MAX, INT_BUFSIZE_BOUND (int))];
228 if (sig2str (sig, signame) != 0)
229 snprintf (signame, sizeof signame, "%d", sig);
230 error (0, 0, _("sending signal %s to command %s"),
231 signame, quote (command));
233 send_sig (monitored_pid, sig);
235 /* The normal case is the job has remained in our
236 newly created process group, so send to all processes in that. */
237 if (!foreground)
239 send_sig (0, sig);
240 if (sig != SIGKILL && sig != SIGCONT)
242 send_sig (monitored_pid, SIGCONT);
243 send_sig (0, SIGCONT);
247 else if (monitored_pid == -1)
248 { /* were in the parent, so let it continue to exit below. */
250 else /* monitored_pid == 0 */
251 { /* parent hasn't forked yet, or child has not exec'd yet. */
252 _exit (128 + sig);
256 void
257 usage (int status)
259 if (status != EXIT_SUCCESS)
260 emit_try_help ();
261 else
263 printf (_("\
264 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
265 or: %s [OPTION]\n"), program_name, program_name);
267 fputs (_("\
268 Start COMMAND, and kill it if still running after DURATION.\n\
269 "), stdout);
271 emit_mandatory_arg_note ();
273 fputs (_("\
274 --preserve-status\n\
275 exit with the same status as COMMAND, even when the\n\
276 command times out\n\
277 --foreground\n\
278 when not running timeout directly from a shell prompt,\n\
279 allow COMMAND to read from the TTY and get TTY signals;\n\
280 in this mode, children of COMMAND will not be timed out\n\
281 -k, --kill-after=DURATION\n\
282 also send a KILL signal if COMMAND is still running\n\
283 this long after the initial signal was sent\n\
284 -s, --signal=SIGNAL\n\
285 specify the signal to be sent on timeout;\n\
286 SIGNAL may be a name like 'HUP' or a number;\n\
287 see 'kill -l' for a list of signals\n"), stdout);
288 fputs (_("\
289 -v, --verbose diagnose to stderr any signal sent upon timeout\n"), stdout);
291 fputs (HELP_OPTION_DESCRIPTION, stdout);
292 fputs (VERSION_OPTION_DESCRIPTION, stdout);
294 fputs (_("\n\
295 DURATION is a floating point number with an optional suffix:\n\
296 's' for seconds (the default), 'm' for minutes, 'h' for hours or \
297 'd' for days.\nA duration of 0 disables the associated timeout.\n"), stdout);
299 fputs (_("\n\
300 Upon timeout, send the TERM signal to COMMAND, if no other SIGNAL specified.\n\
301 The TERM signal kills any process that does not block or catch that signal.\n\
302 It may be necessary to use the KILL signal, since this signal can't be caught.\
303 \n"), stdout);
305 fputs (_("\n\
306 Exit status:\n\
307 124 if COMMAND times out, and --preserve-status is not specified\n\
308 125 if the timeout command itself fails\n\
309 126 if COMMAND is found but cannot be invoked\n\
310 127 if COMMAND cannot be found\n\
311 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)\n\
312 - the exit status of COMMAND otherwise\n\
313 "), stdout);
315 emit_ancillary_info (PROGRAM_NAME);
317 exit (status);
320 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
321 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
322 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
323 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
324 and return false. Otherwise return true. */
326 static bool
327 apply_time_suffix (double *x, char suffix_char)
329 int multiplier;
331 switch (suffix_char)
333 case 0:
334 case 's':
335 multiplier = 1;
336 break;
337 case 'm':
338 multiplier = 60;
339 break;
340 case 'h':
341 multiplier = 60 * 60;
342 break;
343 case 'd':
344 multiplier = 60 * 60 * 24;
345 break;
346 default:
347 return false;
350 *x *= multiplier;
352 return true;
355 static double
356 parse_duration (char const *str)
358 double duration;
359 char const *ep;
361 if (! (xstrtod (str, &ep, &duration, cl_strtod) || errno == ERANGE)
362 /* Nonnegative interval. */
363 || ! (0 <= duration)
364 /* No extra chars after the number and an optional s,m,h,d char. */
365 || (*ep && *(ep + 1))
366 /* Check any suffix char and update timeout based on the suffix. */
367 || !apply_time_suffix (&duration, *ep))
369 error (0, 0, _("invalid time interval %s"), quote (str));
370 usage (EXIT_CANCELED);
373 return duration;
376 static void
377 unblock_signal (int sig)
379 sigset_t unblock_set;
380 sigemptyset (&unblock_set);
381 sigaddset (&unblock_set, sig);
382 if (sigprocmask (SIG_UNBLOCK, &unblock_set, nullptr) != 0)
383 error (0, errno, _("warning: sigprocmask"));
386 static void
387 install_sigchld (void)
389 struct sigaction sa;
390 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
391 sa.sa_handler = chld;
392 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
393 more likely to work cleanly. */
395 sigaction (SIGCHLD, &sa, nullptr);
397 /* We inherit the signal mask from our parent process,
398 so ensure SIGCHLD is not blocked. */
399 unblock_signal (SIGCHLD);
402 static void
403 install_cleanup (int sigterm)
405 struct sigaction sa;
406 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
407 sa.sa_handler = cleanup;
408 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
409 more likely to work cleanly. */
411 sigaction (SIGALRM, &sa, nullptr); /* our timeout. */
412 sigaction (SIGINT, &sa, nullptr); /* Ctrl-C at terminal for example. */
413 sigaction (SIGQUIT, &sa, nullptr); /* Ctrl-\ at terminal for example. */
414 sigaction (SIGHUP, &sa, nullptr); /* terminal closed for example. */
415 sigaction (SIGTERM, &sa, nullptr); /* if killed, stop monitored proc. */
416 sigaction (sigterm, &sa, nullptr); /* user specified termination signal. */
419 /* Block all signals which were registered with cleanup() as the signal
420 handler, so we never kill processes after waitpid() returns.
421 Also block SIGCHLD to ensure it doesn't fire between
422 waitpid() polling and sigsuspend() waiting for a signal.
423 Return original mask in OLD_SET. */
424 static void
425 block_cleanup_and_chld (int sigterm, sigset_t *old_set)
427 sigset_t block_set;
428 sigemptyset (&block_set);
430 sigaddset (&block_set, SIGALRM);
431 sigaddset (&block_set, SIGINT);
432 sigaddset (&block_set, SIGQUIT);
433 sigaddset (&block_set, SIGHUP);
434 sigaddset (&block_set, SIGTERM);
435 sigaddset (&block_set, sigterm);
437 sigaddset (&block_set, SIGCHLD);
439 if (sigprocmask (SIG_BLOCK, &block_set, old_set) != 0)
440 error (0, errno, _("warning: sigprocmask"));
443 /* Try to disable core dumps for this process.
444 Return TRUE if successful, FALSE otherwise. */
445 static bool
446 disable_core_dumps (void)
448 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
449 if (prctl (PR_SET_DUMPABLE, 0) == 0)
450 return true;
452 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
453 /* Note this doesn't disable processing by a filter in
454 /proc/sys/kernel/core_pattern on Linux. */
455 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0}) == 0)
456 return true;
458 #else
459 return false;
460 #endif
462 error (0, errno, _("warning: disabling core dumps failed"));
463 return false;
467 main (int argc, char **argv)
469 double timeout;
470 int c;
472 initialize_main (&argc, &argv);
473 set_program_name (argv[0]);
474 setlocale (LC_ALL, "");
475 bindtextdomain (PACKAGE, LOCALEDIR);
476 textdomain (PACKAGE);
478 initialize_exit_failure (EXIT_CANCELED);
479 atexit (close_stdout);
481 while ((c = getopt_long (argc, argv, "+k:s:v", long_options, nullptr)) != -1)
483 switch (c)
485 case 'k':
486 kill_after = parse_duration (optarg);
487 break;
489 case 's':
490 term_signal = operand2sig (optarg);
491 if (term_signal == -1)
492 usage (EXIT_CANCELED);
493 break;
495 case 'v':
496 verbose = true;
497 break;
499 case FOREGROUND_OPTION:
500 foreground = true;
501 break;
503 case PRESERVE_STATUS_OPTION:
504 preserve_status = true;
505 break;
507 case_GETOPT_HELP_CHAR;
509 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
511 default:
512 usage (EXIT_CANCELED);
513 break;
517 if (argc - optind < 2)
518 usage (EXIT_CANCELED);
520 timeout = parse_duration (argv[optind++]);
522 argv += optind;
523 command = argv[0];
525 /* Ensure we're in our own group so all subprocesses can be killed.
526 Note we don't just put the child in a separate group as
527 then we would need to worry about foreground and background groups
528 and propagating signals between them. */
529 if (!foreground)
530 setpgid (0, 0);
532 /* Setup handlers before fork() so that we
533 handle any signals caused by child, without races. */
534 install_cleanup (term_signal);
535 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
536 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
537 install_sigchld (); /* Interrupt sigsuspend() when child exits. */
539 /* We configure timers so that SIGALRM is sent on expiry.
540 Therefore ensure we don't inherit a mask blocking SIGALRM. */
541 unblock_signal (SIGALRM);
543 /* Block signals now, so monitored_pid is deterministic in cleanup(). */
544 sigset_t orig_set;
545 block_cleanup_and_chld (term_signal, &orig_set);
547 monitored_pid = fork ();
548 if (monitored_pid == -1)
550 error (0, errno, _("fork system call failed"));
551 return EXIT_CANCELED;
553 else if (monitored_pid == 0) /* child */
555 /* Restore signal mask for child. */
556 if (sigprocmask (SIG_SETMASK, &orig_set, nullptr) != 0)
558 error (0, errno, _("child failed to reset signal mask"));
559 return EXIT_CANCELED;
562 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
563 signal (SIGTTIN, SIG_DFL);
564 signal (SIGTTOU, SIG_DFL);
566 execvp (argv[0], argv);
568 /* exit like sh, env, nohup, ... */
569 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
570 error (0, errno, _("failed to run command %s"), quote (command));
571 return exit_status;
573 else
575 pid_t wait_result;
576 int status;
578 settimeout (timeout, true);
580 /* Note signals remain blocked in parent here, to ensure
581 we don't cleanup() after waitpid() reaps the child,
582 to avoid sending signals to a possibly different process. */
584 while ((wait_result = waitpid (monitored_pid, &status, WNOHANG)) == 0)
585 sigsuspend (&orig_set); /* Wait with cleanup signals unblocked. */
587 if (wait_result < 0)
589 /* shouldn't happen. */
590 error (0, errno, _("error waiting for command"));
591 status = EXIT_CANCELED;
593 else
595 if (WIFEXITED (status))
596 status = WEXITSTATUS (status);
597 else if (WIFSIGNALED (status))
599 int sig = WTERMSIG (status);
600 if (WCOREDUMP (status))
601 error (0, 0, _("the monitored command dumped core"));
602 if (!timed_out && disable_core_dumps ())
604 /* exit with the signal flag set. */
605 signal (sig, SIG_DFL);
606 unblock_signal (sig);
607 raise (sig);
609 /* Allow users to distinguish if command was forcibly killed.
610 Needed with --foreground where we don't send SIGKILL to
611 the timeout process itself. */
612 if (timed_out && sig == SIGKILL)
613 preserve_status = true;
614 status = sig + 128; /* what sh returns for signaled processes. */
616 else
618 /* shouldn't happen. */
619 error (0, 0, _("unknown status from command (%d)"), status);
620 status = EXIT_FAILURE;
624 if (timed_out && !preserve_status)
625 status = EXIT_TIMEDOUT;
626 return status;