chgrp: add --from parameter similar to chown
[coreutils.git] / src / timeout.c
blob88a1190d0519618ab8861803acdc35b6e5bade3f
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 "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 (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 /* we're the child or the child is not exec'd yet. */
248 _exit (128 + sig);
251 void
252 usage (int status)
254 if (status != EXIT_SUCCESS)
255 emit_try_help ();
256 else
258 printf (_("\
259 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
260 or: %s [OPTION]\n"), program_name, program_name);
262 fputs (_("\
263 Start COMMAND, and kill it if still running after DURATION.\n\
264 "), stdout);
266 emit_mandatory_arg_note ();
268 fputs (_("\
269 --preserve-status\n\
270 exit with the same status as COMMAND, even when the\n\
271 command times out\n\
272 --foreground\n\
273 when not running timeout directly from a shell prompt,\n\
274 allow COMMAND to read from the TTY and get TTY signals;\n\
275 in this mode, children of COMMAND will not be timed out\n\
276 -k, --kill-after=DURATION\n\
277 also send a KILL signal if COMMAND is still running\n\
278 this long after the initial signal was sent\n\
279 -s, --signal=SIGNAL\n\
280 specify the signal to be sent on timeout;\n\
281 SIGNAL may be a name like 'HUP' or a number;\n\
282 see 'kill -l' for a list of signals\n"), stdout);
283 fputs (_("\
284 -v, --verbose diagnose to stderr any signal sent upon timeout\n"), stdout);
286 fputs (HELP_OPTION_DESCRIPTION, stdout);
287 fputs (VERSION_OPTION_DESCRIPTION, stdout);
289 fputs (_("\n\
290 DURATION is a floating point number with an optional suffix:\n\
291 's' for seconds (the default), 'm' for minutes, 'h' for hours or \
292 'd' for days.\nA duration of 0 disables the associated timeout.\n"), stdout);
294 fputs (_("\n\
295 Upon timeout, send the TERM signal to COMMAND, if no other SIGNAL specified.\n\
296 The TERM signal kills any process that does not block or catch that signal.\n\
297 It may be necessary to use the KILL signal, since this signal can't be caught.\
298 \n"), stdout);
300 fputs (_("\n\
301 Exit status:\n\
302 124 if COMMAND times out, and --preserve-status is not specified\n\
303 125 if the timeout command itself fails\n\
304 126 if COMMAND is found but cannot be invoked\n\
305 127 if COMMAND cannot be found\n\
306 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)\n\
307 - the exit status of COMMAND otherwise\n\
308 "), stdout);
310 emit_ancillary_info (PROGRAM_NAME);
312 exit (status);
315 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
316 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
317 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
318 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
319 and return false. Otherwise return true. */
321 static bool
322 apply_time_suffix (double *x, char suffix_char)
324 int multiplier;
326 switch (suffix_char)
328 case 0:
329 case 's':
330 multiplier = 1;
331 break;
332 case 'm':
333 multiplier = 60;
334 break;
335 case 'h':
336 multiplier = 60 * 60;
337 break;
338 case 'd':
339 multiplier = 60 * 60 * 24;
340 break;
341 default:
342 return false;
345 *x *= multiplier;
347 return true;
350 static double
351 parse_duration (char const *str)
353 double duration;
354 char const *ep;
356 if (! (xstrtod (str, &ep, &duration, cl_strtod) || errno == ERANGE)
357 /* Nonnegative interval. */
358 || ! (0 <= duration)
359 /* No extra chars after the number and an optional s,m,h,d char. */
360 || (*ep && *(ep + 1))
361 /* Check any suffix char and update timeout based on the suffix. */
362 || !apply_time_suffix (&duration, *ep))
364 error (0, 0, _("invalid time interval %s"), quote (str));
365 usage (EXIT_CANCELED);
368 return duration;
371 static void
372 unblock_signal (int sig)
374 sigset_t unblock_set;
375 sigemptyset (&unblock_set);
376 sigaddset (&unblock_set, sig);
377 if (sigprocmask (SIG_UNBLOCK, &unblock_set, nullptr) != 0)
378 error (0, errno, _("warning: sigprocmask"));
381 static void
382 install_sigchld (void)
384 struct sigaction sa;
385 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
386 sa.sa_handler = chld;
387 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
388 more likely to work cleanly. */
390 sigaction (SIGCHLD, &sa, nullptr);
392 /* We inherit the signal mask from our parent process,
393 so ensure SIGCHLD is not blocked. */
394 unblock_signal (SIGCHLD);
397 static void
398 install_cleanup (int sigterm)
400 struct sigaction sa;
401 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
402 sa.sa_handler = cleanup;
403 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
404 more likely to work cleanly. */
406 sigaction (SIGALRM, &sa, nullptr); /* our timeout. */
407 sigaction (SIGINT, &sa, nullptr); /* Ctrl-C at terminal for example. */
408 sigaction (SIGQUIT, &sa, nullptr); /* Ctrl-\ at terminal for example. */
409 sigaction (SIGHUP, &sa, nullptr); /* terminal closed for example. */
410 sigaction (SIGTERM, &sa, nullptr); /* if killed, stop monitored proc. */
411 sigaction (sigterm, &sa, nullptr); /* user specified termination signal. */
414 /* Block all signals which were registered with cleanup() as the signal
415 handler, so we never kill processes after waitpid() returns.
416 Also block SIGCHLD to ensure it doesn't fire between
417 waitpid() polling and sigsuspend() waiting for a signal.
418 Return original mask in OLD_SET. */
419 static void
420 block_cleanup_and_chld (int sigterm, sigset_t *old_set)
422 sigset_t block_set;
423 sigemptyset (&block_set);
425 sigaddset (&block_set, SIGALRM);
426 sigaddset (&block_set, SIGINT);
427 sigaddset (&block_set, SIGQUIT);
428 sigaddset (&block_set, SIGHUP);
429 sigaddset (&block_set, SIGTERM);
430 sigaddset (&block_set, sigterm);
432 sigaddset (&block_set, SIGCHLD);
434 if (sigprocmask (SIG_BLOCK, &block_set, old_set) != 0)
435 error (0, errno, _("warning: sigprocmask"));
438 /* Try to disable core dumps for this process.
439 Return TRUE if successful, FALSE otherwise. */
440 static bool
441 disable_core_dumps (void)
443 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
444 if (prctl (PR_SET_DUMPABLE, 0) == 0)
445 return true;
447 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
448 /* Note this doesn't disable processing by a filter in
449 /proc/sys/kernel/core_pattern on Linux. */
450 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0}) == 0)
451 return true;
453 #else
454 return false;
455 #endif
457 error (0, errno, _("warning: disabling core dumps failed"));
458 return false;
462 main (int argc, char **argv)
464 double timeout;
465 char signame[SIG2STR_MAX];
466 int c;
468 initialize_main (&argc, &argv);
469 set_program_name (argv[0]);
470 setlocale (LC_ALL, "");
471 bindtextdomain (PACKAGE, LOCALEDIR);
472 textdomain (PACKAGE);
474 initialize_exit_failure (EXIT_CANCELED);
475 atexit (close_stdout);
477 while ((c = getopt_long (argc, argv, "+k:s:v", long_options, nullptr)) != -1)
479 switch (c)
481 case 'k':
482 kill_after = parse_duration (optarg);
483 break;
485 case 's':
486 term_signal = operand2sig (optarg, signame);
487 if (term_signal == -1)
488 usage (EXIT_CANCELED);
489 break;
491 case 'v':
492 verbose = true;
493 break;
495 case FOREGROUND_OPTION:
496 foreground = true;
497 break;
499 case PRESERVE_STATUS_OPTION:
500 preserve_status = true;
501 break;
503 case_GETOPT_HELP_CHAR;
505 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
507 default:
508 usage (EXIT_CANCELED);
509 break;
513 if (argc - optind < 2)
514 usage (EXIT_CANCELED);
516 timeout = parse_duration (argv[optind++]);
518 argv += optind;
519 command = argv[0];
521 /* Ensure we're in our own group so all subprocesses can be killed.
522 Note we don't just put the child in a separate group as
523 then we would need to worry about foreground and background groups
524 and propagating signals between them. */
525 if (!foreground)
526 setpgid (0, 0);
528 /* Setup handlers before fork() so that we
529 handle any signals caused by child, without races. */
530 install_cleanup (term_signal);
531 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
532 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
533 install_sigchld (); /* Interrupt sigsuspend() when child exits. */
535 monitored_pid = fork ();
536 if (monitored_pid == -1)
538 error (0, errno, _("fork system call failed"));
539 return EXIT_CANCELED;
541 else if (monitored_pid == 0)
542 { /* child */
543 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
544 signal (SIGTTIN, SIG_DFL);
545 signal (SIGTTOU, SIG_DFL);
547 execvp (argv[0], argv);
549 /* exit like sh, env, nohup, ... */
550 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
551 error (0, errno, _("failed to run command %s"), quote (command));
552 return exit_status;
554 else
556 pid_t wait_result;
557 int status;
559 /* We configure timers so that SIGALRM is sent on expiry.
560 Therefore ensure we don't inherit a mask blocking SIGALRM. */
561 unblock_signal (SIGALRM);
563 settimeout (timeout, true);
565 /* Ensure we don't cleanup() after waitpid() reaps the child,
566 to avoid sending signals to a possibly different process. */
567 sigset_t cleanup_set;
568 block_cleanup_and_chld (term_signal, &cleanup_set);
570 while ((wait_result = waitpid (monitored_pid, &status, WNOHANG)) == 0)
571 sigsuspend (&cleanup_set); /* Wait with cleanup signals unblocked. */
573 if (wait_result < 0)
575 /* shouldn't happen. */
576 error (0, errno, _("error waiting for command"));
577 status = EXIT_CANCELED;
579 else
581 if (WIFEXITED (status))
582 status = WEXITSTATUS (status);
583 else if (WIFSIGNALED (status))
585 int sig = WTERMSIG (status);
586 if (WCOREDUMP (status))
587 error (0, 0, _("the monitored command dumped core"));
588 if (!timed_out && disable_core_dumps ())
590 /* exit with the signal flag set. */
591 signal (sig, SIG_DFL);
592 unblock_signal (sig);
593 raise (sig);
595 /* Allow users to distinguish if command was forcibly killed.
596 Needed with --foreground where we don't send SIGKILL to
597 the timeout process itself. */
598 if (timed_out && sig == SIGKILL)
599 preserve_status = true;
600 status = sig + 128; /* what sh returns for signaled processes. */
602 else
604 /* shouldn't happen. */
605 error (0, 0, _("unknown status from command (%d)"), status);
606 status = EXIT_FAILURE;
610 if (timed_out && !preserve_status)
611 status = EXIT_TIMEDOUT;
612 return status;