split: port ‘split -n N /dev/null’ better to macOS
[coreutils.git] / src / timeout.c
blob34cf49e3289c2ddf0ea5ab1c30140ccd704b3a8b
1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2023 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 "error.h"
63 #include "quote.h"
65 #if HAVE_SETRLIMIT
66 /* FreeBSD 5.0 at least needs <sys/types.h> and <sys/time.h> included
67 before <sys/resource.h>. Currently "system.h" includes <sys/time.h>. */
68 # include <sys/resource.h>
69 #endif
71 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt. */
72 #ifndef SA_RESTART
73 # define SA_RESTART 0
74 #endif
76 #define PROGRAM_NAME "timeout"
78 #define AUTHORS proper_name ("Padraig Brady")
80 static int timed_out;
81 static int term_signal = SIGTERM; /* same default as kill command. */
82 static pid_t monitored_pid;
83 static double kill_after;
84 static bool foreground; /* whether to use another program group. */
85 static bool preserve_status; /* whether to use a timeout status or not. */
86 static bool verbose; /* whether to diagnose timeouts or not. */
87 static char const *command;
89 /* for long options with no corresponding short option, use enum */
90 enum
92 FOREGROUND_OPTION = CHAR_MAX + 1,
93 PRESERVE_STATUS_OPTION
96 static struct option const long_options[] =
98 {"kill-after", required_argument, NULL, 'k'},
99 {"signal", required_argument, NULL, 's'},
100 {"verbose", no_argument, NULL, 'v'},
101 {"foreground", no_argument, NULL, FOREGROUND_OPTION},
102 {"preserve-status", no_argument, NULL, PRESERVE_STATUS_OPTION},
103 {GETOPT_HELP_OPTION_DECL},
104 {GETOPT_VERSION_OPTION_DECL},
105 {NULL, 0, NULL, 0}
108 /* Start the timeout after which we'll receive a SIGALRM.
109 Round DURATION up to the next representable value.
110 Treat out-of-range values as if they were maximal,
111 as that's more useful in practice than reporting an error.
112 '0' means don't timeout. */
113 static void
114 settimeout (double duration, bool warn)
117 #if HAVE_TIMER_SETTIME
118 /* timer_settime() provides potentially nanosecond resolution. */
120 struct timespec ts = dtotimespec (duration);
121 struct itimerspec its = { {0, 0}, ts };
122 timer_t timerid;
123 if (timer_create (CLOCK_REALTIME, NULL, &timerid) == 0)
125 if (timer_settime (timerid, 0, &its, NULL) == 0)
126 return;
127 else
129 if (warn)
130 error (0, errno, _("warning: timer_settime"));
131 timer_delete (timerid);
134 else if (warn && errno != ENOSYS)
135 error (0, errno, _("warning: timer_create"));
137 #elif HAVE_SETITIMER
138 /* setitimer() is more portable (to Darwin for example),
139 but only provides microsecond resolution. */
141 struct timeval tv;
142 struct timespec ts = dtotimespec (duration);
143 tv.tv_sec = ts.tv_sec;
144 tv.tv_usec = (ts.tv_nsec + 999) / 1000;
145 if (tv.tv_usec == 1000 * 1000)
147 if (tv.tv_sec != TYPE_MAXIMUM (time_t))
149 tv.tv_sec++;
150 tv.tv_usec = 0;
152 else
153 tv.tv_usec--;
155 struct itimerval it = { {0, 0}, tv };
156 if (setitimer (ITIMER_REAL, &it, NULL) == 0)
157 return;
158 else
160 if (warn && errno != ENOSYS)
161 error (0, errno, _("warning: setitimer"));
163 #endif
165 /* fallback to single second resolution provided by alarm(). */
167 unsigned int timeint;
168 if (UINT_MAX <= duration)
169 timeint = UINT_MAX;
170 else
172 unsigned int duration_floor = duration;
173 timeint = duration_floor + (duration_floor < duration);
175 alarm (timeint);
178 /* send SIG avoiding the current process. */
180 static int
181 send_sig (pid_t where, int sig)
183 /* If sending to the group, then ignore the signal,
184 so we don't go into a signal loop. Note that this will ignore any of the
185 signals registered in install_cleanup(), that are sent after we
186 propagate the first one, which hopefully won't be an issue. Note this
187 process can be implicitly multithreaded due to some timer_settime()
188 implementations, therefore a signal sent to the group, can be sent
189 multiple times to this process. */
190 if (where == 0)
191 signal (sig, SIG_IGN);
192 return kill (where, sig);
195 /* Signal handler which is required for sigsuspend() to be interrupted
196 whenever SIGCHLD is received. */
197 static void
198 chld (int sig)
203 static void
204 cleanup (int sig)
206 if (sig == SIGALRM)
208 timed_out = 1;
209 sig = term_signal;
211 if (monitored_pid)
213 if (kill_after)
215 int saved_errno = errno; /* settimeout may reset. */
216 /* Start a new timeout after which we'll send SIGKILL. */
217 term_signal = SIGKILL;
218 settimeout (kill_after, false);
219 kill_after = 0; /* Don't let later signals reset kill alarm. */
220 errno = saved_errno;
223 /* Send the signal directly to the monitored child,
224 in case it has itself become group leader,
225 or is not running in a separate group. */
226 if (verbose)
228 char signame[MAX (SIG2STR_MAX, INT_BUFSIZE_BOUND (int))];
229 if (sig2str (sig, signame) != 0)
230 snprintf (signame, sizeof signame, "%d", sig);
231 error (0, 0, _("sending signal %s to command %s"),
232 signame, quote (command));
234 send_sig (monitored_pid, sig);
236 /* The normal case is the job has remained in our
237 newly created process group, so send to all processes in that. */
238 if (!foreground)
240 send_sig (0, sig);
241 if (sig != SIGKILL && sig != SIGCONT)
243 send_sig (monitored_pid, SIGCONT);
244 send_sig (0, SIGCONT);
248 else /* we're the child or the child is not exec'd yet. */
249 _exit (128 + sig);
252 void
253 usage (int status)
255 if (status != EXIT_SUCCESS)
256 emit_try_help ();
257 else
259 printf (_("\
260 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
261 or: %s [OPTION]\n"), program_name, program_name);
263 fputs (_("\
264 Start COMMAND, and kill it if still running after DURATION.\n\
265 "), stdout);
267 emit_mandatory_arg_note ();
269 fputs (_("\
270 --preserve-status\n\
271 exit with the same status as COMMAND, even when the\n\
272 command times out\n\
273 --foreground\n\
274 when not running timeout directly from a shell prompt,\n\
275 allow COMMAND to read from the TTY and get TTY signals;\n\
276 in this mode, children of COMMAND will not be timed out\n\
277 -k, --kill-after=DURATION\n\
278 also send a KILL signal if COMMAND is still running\n\
279 this long after the initial signal was sent\n\
280 -s, --signal=SIGNAL\n\
281 specify the signal to be sent on timeout;\n\
282 SIGNAL may be a name like 'HUP' or a number;\n\
283 see 'kill -l' for a list of signals\n"), stdout);
284 fputs (_("\
285 -v, --verbose diagnose to stderr any signal sent upon timeout\n"), stdout);
287 fputs (HELP_OPTION_DESCRIPTION, stdout);
288 fputs (VERSION_OPTION_DESCRIPTION, stdout);
290 fputs (_("\n\
291 DURATION is a floating point number with an optional suffix:\n\
292 's' for seconds (the default), 'm' for minutes, 'h' for hours or \
293 'd' for days.\nA duration of 0 disables the associated timeout.\n"), stdout);
295 fputs (_("\n\
296 Upon timeout, send the TERM signal to COMMAND, if no other SIGNAL specified.\n\
297 The TERM signal kills any process that does not block or catch that signal.\n\
298 It may be necessary to use the KILL signal, since this signal can't be caught.\
299 \n"), stdout);
301 fputs (_("\n\
302 Exit status:\n\
303 124 if COMMAND times out, and --preserve-status is not specified\n\
304 125 if the timeout command itself fails\n\
305 126 if COMMAND is found but cannot be invoked\n\
306 127 if COMMAND cannot be found\n\
307 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)\n\
308 - the exit status of COMMAND otherwise\n\
309 "), stdout);
311 emit_ancillary_info (PROGRAM_NAME);
313 exit (status);
316 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
317 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
318 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
319 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
320 and return false. Otherwise return true. */
322 static bool
323 apply_time_suffix (double *x, char suffix_char)
325 int multiplier;
327 switch (suffix_char)
329 case 0:
330 case 's':
331 multiplier = 1;
332 break;
333 case 'm':
334 multiplier = 60;
335 break;
336 case 'h':
337 multiplier = 60 * 60;
338 break;
339 case 'd':
340 multiplier = 60 * 60 * 24;
341 break;
342 default:
343 return false;
346 *x *= multiplier;
348 return true;
351 static double
352 parse_duration (char const *str)
354 double duration;
355 char const *ep;
357 if (! (xstrtod (str, &ep, &duration, cl_strtod) || errno == ERANGE)
358 /* Nonnegative interval. */
359 || ! (0 <= duration)
360 /* No extra chars after the number and an optional s,m,h,d char. */
361 || (*ep && *(ep + 1))
362 /* Check any suffix char and update timeout based on the suffix. */
363 || !apply_time_suffix (&duration, *ep))
365 error (0, 0, _("invalid time interval %s"), quote (str));
366 usage (EXIT_CANCELED);
369 return duration;
372 static void
373 unblock_signal (int sig)
375 sigset_t unblock_set;
376 sigemptyset (&unblock_set);
377 sigaddset (&unblock_set, sig);
378 if (sigprocmask (SIG_UNBLOCK, &unblock_set, NULL) != 0)
379 error (0, errno, _("warning: sigprocmask"));
382 static void
383 install_sigchld (void)
385 struct sigaction sa;
386 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
387 sa.sa_handler = chld;
388 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
389 more likely to work cleanly. */
391 sigaction (SIGCHLD, &sa, NULL);
393 /* We inherit the signal mask from our parent process,
394 so ensure SIGCHLD is not blocked. */
395 unblock_signal (SIGCHLD);
398 static void
399 install_cleanup (int sigterm)
401 struct sigaction sa;
402 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
403 sa.sa_handler = cleanup;
404 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
405 more likely to work cleanly. */
407 sigaction (SIGALRM, &sa, NULL); /* our timeout. */
408 sigaction (SIGINT, &sa, NULL); /* Ctrl-C at terminal for example. */
409 sigaction (SIGQUIT, &sa, NULL); /* Ctrl-\ at terminal for example. */
410 sigaction (SIGHUP, &sa, NULL); /* terminal closed for example. */
411 sigaction (SIGTERM, &sa, NULL); /* if we're killed, stop monitored proc. */
412 sigaction (sigterm, &sa, NULL); /* user specified termination signal. */
415 /* Block all signals which were registered with cleanup() as the signal
416 handler, so we never kill processes after waitpid() returns.
417 Also block SIGCHLD to ensure it doesn't fire between
418 waitpid() polling and sigsuspend() waiting for a signal.
419 Return original mask in OLD_SET. */
420 static void
421 block_cleanup_and_chld (int sigterm, sigset_t *old_set)
423 sigset_t block_set;
424 sigemptyset (&block_set);
426 sigaddset (&block_set, SIGALRM);
427 sigaddset (&block_set, SIGINT);
428 sigaddset (&block_set, SIGQUIT);
429 sigaddset (&block_set, SIGHUP);
430 sigaddset (&block_set, SIGTERM);
431 sigaddset (&block_set, sigterm);
433 sigaddset (&block_set, SIGCHLD);
435 if (sigprocmask (SIG_BLOCK, &block_set, old_set) != 0)
436 error (0, errno, _("warning: sigprocmask"));
439 /* Try to disable core dumps for this process.
440 Return TRUE if successful, FALSE otherwise. */
441 static bool
442 disable_core_dumps (void)
444 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
445 if (prctl (PR_SET_DUMPABLE, 0) == 0)
446 return true;
448 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
449 /* Note this doesn't disable processing by a filter in
450 /proc/sys/kernel/core_pattern on Linux. */
451 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0,0}) == 0)
452 return true;
454 #else
455 return false;
456 #endif
458 error (0, errno, _("warning: disabling core dumps failed"));
459 return false;
463 main (int argc, char **argv)
465 double timeout;
466 char signame[SIG2STR_MAX];
467 int c;
469 initialize_main (&argc, &argv);
470 set_program_name (argv[0]);
471 setlocale (LC_ALL, "");
472 bindtextdomain (PACKAGE, LOCALEDIR);
473 textdomain (PACKAGE);
475 initialize_exit_failure (EXIT_CANCELED);
476 atexit (close_stdout);
478 while ((c = getopt_long (argc, argv, "+k:s:v", long_options, NULL)) != -1)
480 switch (c)
482 case 'k':
483 kill_after = parse_duration (optarg);
484 break;
486 case 's':
487 term_signal = operand2sig (optarg, signame);
488 if (term_signal == -1)
489 usage (EXIT_CANCELED);
490 break;
492 case 'v':
493 verbose = true;
494 break;
496 case FOREGROUND_OPTION:
497 foreground = true;
498 break;
500 case PRESERVE_STATUS_OPTION:
501 preserve_status = true;
502 break;
504 case_GETOPT_HELP_CHAR;
506 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
508 default:
509 usage (EXIT_CANCELED);
510 break;
514 if (argc - optind < 2)
515 usage (EXIT_CANCELED);
517 timeout = parse_duration (argv[optind++]);
519 argv += optind;
520 command = argv[0];
522 /* Ensure we're in our own group so all subprocesses can be killed.
523 Note we don't just put the child in a separate group as
524 then we would need to worry about foreground and background groups
525 and propagating signals between them. */
526 if (!foreground)
527 setpgid (0, 0);
529 /* Setup handlers before fork() so that we
530 handle any signals caused by child, without races. */
531 install_cleanup (term_signal);
532 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
533 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
534 install_sigchld (); /* Interrupt sigsuspend() when child exits. */
536 monitored_pid = fork ();
537 if (monitored_pid == -1)
539 error (0, errno, _("fork system call failed"));
540 return EXIT_CANCELED;
542 else if (monitored_pid == 0)
543 { /* child */
544 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
545 signal (SIGTTIN, SIG_DFL);
546 signal (SIGTTOU, SIG_DFL);
548 execvp (argv[0], argv);
550 /* exit like sh, env, nohup, ... */
551 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
552 error (0, errno, _("failed to run command %s"), quote (command));
553 return exit_status;
555 else
557 pid_t wait_result;
558 int status;
560 /* We configure timers so that SIGALRM is sent on expiry.
561 Therefore ensure we don't inherit a mask blocking SIGALRM. */
562 unblock_signal (SIGALRM);
564 settimeout (timeout, true);
566 /* Ensure we don't cleanup() after waitpid() reaps the child,
567 to avoid sending signals to a possibly different process. */
568 sigset_t cleanup_set;
569 block_cleanup_and_chld (term_signal, &cleanup_set);
571 while ((wait_result = waitpid (monitored_pid, &status, WNOHANG)) == 0)
572 sigsuspend (&cleanup_set); /* Wait with cleanup signals unblocked. */
574 if (wait_result < 0)
576 /* shouldn't happen. */
577 error (0, errno, _("error waiting for command"));
578 status = EXIT_CANCELED;
580 else
582 if (WIFEXITED (status))
583 status = WEXITSTATUS (status);
584 else if (WIFSIGNALED (status))
586 int sig = WTERMSIG (status);
587 if (WCOREDUMP (status))
588 error (0, 0, _("the monitored command dumped core"));
589 if (!timed_out && disable_core_dumps ())
591 /* exit with the signal flag set. */
592 signal (sig, SIG_DFL);
593 unblock_signal (sig);
594 raise (sig);
596 /* Allow users to distinguish if command was forcably killed.
597 Needed with --foreground where we don't send SIGKILL to
598 the timeout process itself. */
599 if (timed_out && sig == SIGKILL)
600 preserve_status = true;
601 status = sig + 128; /* what sh returns for signaled processes. */
603 else
605 /* shouldn't happen. */
606 error (0, 0, _("unknown status from command (%d)"), status);
607 status = EXIT_FAILURE;
611 if (timed_out && !preserve_status)
612 status = EXIT_TIMEDOUT;
613 return status;