doc: clarify the operation of wc -L
[coreutils.git] / src / timeout.c
blob19c07653a944f04f1563eb04b80b8c407bb83f4c
1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2015 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 <http://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 "c-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_utf8 ("Padraig Brady", "P\303\241draig Brady")
80 static int timed_out;
81 static int term_signal = SIGTERM; /* same default as kill command. */
82 static int 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. */
87 /* for long options with no corresponding short option, use enum */
88 enum
90 FOREGROUND_OPTION = CHAR_MAX + 1,
91 PRESERVE_STATUS_OPTION
94 static struct option const long_options[] =
96 {"kill-after", required_argument, NULL, 'k'},
97 {"signal", required_argument, NULL, 's'},
98 {"foreground", no_argument, NULL, FOREGROUND_OPTION},
99 {"preserve-status", no_argument, NULL, PRESERVE_STATUS_OPTION},
100 {GETOPT_HELP_OPTION_DECL},
101 {GETOPT_VERSION_OPTION_DECL},
102 {NULL, 0, NULL, 0}
105 static void
106 unblock_signal (int sig)
108 sigset_t unblock_set;
109 sigemptyset (&unblock_set);
110 sigaddset (&unblock_set, sig);
111 if (sigprocmask (SIG_UNBLOCK, &unblock_set, NULL) != 0)
112 error (0, errno, _("warning: sigprocmask"));
115 /* Start the timeout after which we'll receive a SIGALRM.
116 Round DURATION up to the next representable value.
117 Treat out-of-range values as if they were maximal,
118 as that's more useful in practice than reporting an error.
119 '0' means don't timeout. */
120 static void
121 settimeout (double duration, bool warn)
124 /* We configure timers below so that SIGALRM is sent on expiry.
125 Therefore ensure we don't inherit a mask blocking SIGALRM. */
126 unblock_signal (SIGALRM);
128 /* timer_settime() provides potentially nanosecond resolution.
129 setitimer() is more portable (to Darwin for example),
130 but only provides microsecond resolution and thus is
131 a little more awkward to use with timespecs, as well as being
132 deprecated by POSIX. Instead we fallback to single second
133 resolution provided by alarm(). */
135 #if HAVE_TIMER_SETTIME
136 struct timespec ts = dtotimespec (duration);
137 struct itimerspec its = { {0, 0}, ts };
138 timer_t timerid;
139 if (timer_create (CLOCK_REALTIME, NULL, &timerid) == 0)
141 if (timer_settime (timerid, 0, &its, NULL) == 0)
142 return;
143 else
145 if (warn)
146 error (0, errno, _("warning: timer_settime"));
147 timer_delete (timerid);
150 else if (warn && errno != ENOSYS)
151 error (0, errno, _("warning: timer_create"));
152 #endif
154 unsigned int timeint;
155 if (UINT_MAX <= duration)
156 timeint = UINT_MAX;
157 else
159 unsigned int duration_floor = duration;
160 timeint = duration_floor + (duration_floor < duration);
162 alarm (timeint);
165 /* send SIG avoiding the current process. */
167 static int
168 send_sig (int where, int sig)
170 /* If sending to the group, then ignore the signal,
171 so we don't go into a signal loop. Note that this will ignore any of the
172 signals registered in install_signal_handlers(), that are sent after we
173 propagate the first one, which hopefully won't be an issue. Note this
174 process can be implicitly multithreaded due to some timer_settime()
175 implementations, therefore a signal sent to the group, can be sent
176 multiple times to this process. */
177 if (where == 0)
178 signal (sig, SIG_IGN);
179 return kill (where, sig);
182 static void
183 cleanup (int sig)
185 if (sig == SIGALRM)
187 timed_out = 1;
188 sig = term_signal;
190 if (monitored_pid)
192 if (kill_after)
194 int saved_errno = errno; /* settimeout may reset. */
195 /* Start a new timeout after which we'll send SIGKILL. */
196 term_signal = SIGKILL;
197 settimeout (kill_after, false);
198 kill_after = 0; /* Don't let later signals reset kill alarm. */
199 errno = saved_errno;
202 /* Send the signal directly to the monitored child,
203 in case it has itself become group leader,
204 or is not running in a separate group. */
205 send_sig (monitored_pid, sig);
206 /* The normal case is the job has remained in our
207 newly created process group, so send to all processes in that. */
208 if (!foreground)
209 send_sig (0, sig);
210 if (sig != SIGKILL && sig != SIGCONT)
212 send_sig (monitored_pid, SIGCONT);
213 if (!foreground)
214 send_sig (0, SIGCONT);
217 else /* we're the child or the child is not exec'd yet. */
218 _exit (128 + sig);
221 void
222 usage (int status)
224 if (status != EXIT_SUCCESS)
225 emit_try_help ();
226 else
228 printf (_("\
229 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
230 or: %s [OPTION]\n"), program_name, program_name);
232 fputs (_("\
233 Start COMMAND, and kill it if still running after DURATION.\n\
234 "), stdout);
236 emit_mandatory_arg_note ();
238 fputs (_("\
239 --preserve-status\n\
240 exit with the same status as COMMAND, even when the\n\
241 command times out\n\
242 --foreground\n\
243 when not running timeout directly from a shell prompt,\n\
244 allow COMMAND to read from the TTY and get TTY signals;\n\
245 in this mode, children of COMMAND will not be timed out\n\
246 -k, --kill-after=DURATION\n\
247 also send a KILL signal if COMMAND is still running\n\
248 this long after the initial signal was sent\n\
249 -s, --signal=SIGNAL\n\
250 specify the signal to be sent on timeout;\n\
251 SIGNAL may be a name like 'HUP' or a number;\n\
252 see 'kill -l' for a list of signals\n"), stdout);
254 fputs (HELP_OPTION_DESCRIPTION, stdout);
255 fputs (VERSION_OPTION_DESCRIPTION, stdout);
257 fputs (_("\n\
258 DURATION is a floating point number with an optional suffix:\n\
259 's' for seconds (the default), 'm' for minutes, 'h' for hours \
260 or 'd' for days.\n"), stdout);
262 fputs (_("\n\
263 If the command times out, and --preserve-status is not set, then exit with\n\
264 status 124. Otherwise, exit with the status of COMMAND. If no signal\n\
265 is specified, send the TERM signal upon timeout. The TERM signal kills\n\
266 any process that does not block or catch that signal. It may be necessary\n\
267 to use the KILL (9) signal, since this signal cannot be caught, in which\n\
268 case the exit status is 128+9 rather than 124.\n"), stdout);
269 emit_ancillary_info (PROGRAM_NAME);
271 exit (status);
274 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
275 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
276 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
277 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
278 and return false. Otherwise return true. */
280 static bool
281 apply_time_suffix (double *x, char suffix_char)
283 int multiplier;
285 switch (suffix_char)
287 case 0:
288 case 's':
289 multiplier = 1;
290 break;
291 case 'm':
292 multiplier = 60;
293 break;
294 case 'h':
295 multiplier = 60 * 60;
296 break;
297 case 'd':
298 multiplier = 60 * 60 * 24;
299 break;
300 default:
301 return false;
304 *x *= multiplier;
306 return true;
309 static double
310 parse_duration (const char* str)
312 double duration;
313 const char *ep;
315 if (!xstrtod (str, &ep, &duration, c_strtod)
316 /* Nonnegative interval. */
317 || ! (0 <= duration)
318 /* No extra chars after the number and an optional s,m,h,d char. */
319 || (*ep && *(ep + 1))
320 /* Check any suffix char and update timeout based on the suffix. */
321 || !apply_time_suffix (&duration, *ep))
323 error (0, 0, _("invalid time interval %s"), quote (str));
324 usage (EXIT_CANCELED);
327 return duration;
330 static void
331 install_signal_handlers (int sigterm)
333 struct sigaction sa;
334 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
335 sa.sa_handler = cleanup;
336 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
337 more likely to work cleanly. */
339 sigaction (SIGALRM, &sa, NULL); /* our timeout. */
340 sigaction (SIGINT, &sa, NULL); /* Ctrl-C at terminal for example. */
341 sigaction (SIGQUIT, &sa, NULL); /* Ctrl-\ at terminal for example. */
342 sigaction (SIGHUP, &sa, NULL); /* terminal closed for example. */
343 sigaction (SIGTERM, &sa, NULL); /* if we're killed, stop monitored proc. */
344 sigaction (sigterm, &sa, NULL); /* user specified termination signal. */
347 /* Try to disable core dumps for this process.
348 Return TRUE if successful, FALSE otherwise. */
349 static bool
350 disable_core_dumps (void)
352 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
353 if (prctl (PR_SET_DUMPABLE, 0) == 0)
354 return true;
356 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
357 /* Note this doesn't disable processing by a filter in
358 /proc/sys/kernel/core_pattern on Linux. */
359 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0,0}) == 0)
360 return true;
362 #else
363 return false;
364 #endif
366 error (0, errno, _("warning: disabling core dumps failed"));
367 return false;
371 main (int argc, char **argv)
373 double timeout;
374 char signame[SIG2STR_MAX];
375 int c;
377 initialize_main (&argc, &argv);
378 set_program_name (argv[0]);
379 setlocale (LC_ALL, "");
380 bindtextdomain (PACKAGE, LOCALEDIR);
381 textdomain (PACKAGE);
383 initialize_exit_failure (EXIT_CANCELED);
384 atexit (close_stdout);
386 while ((c = getopt_long (argc, argv, "+k:s:", long_options, NULL)) != -1)
388 switch (c)
390 case 'k':
391 kill_after = parse_duration (optarg);
392 break;
394 case 's':
395 term_signal = operand2sig (optarg, signame);
396 if (term_signal == -1)
397 usage (EXIT_CANCELED);
398 break;
400 case FOREGROUND_OPTION:
401 foreground = true;
402 break;
404 case PRESERVE_STATUS_OPTION:
405 preserve_status = true;
406 break;
408 case_GETOPT_HELP_CHAR;
410 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
412 default:
413 usage (EXIT_CANCELED);
414 break;
418 if (argc - optind < 2)
419 usage (EXIT_CANCELED);
421 timeout = parse_duration (argv[optind++]);
423 argv += optind;
425 /* Ensure we're in our own group so all subprocesses can be killed.
426 Note we don't just put the child in a separate group as
427 then we would need to worry about foreground and background groups
428 and propagating signals between them. */
429 if (!foreground)
430 setpgid (0, 0);
432 /* Setup handlers before fork() so that we
433 handle any signals caused by child, without races. */
434 install_signal_handlers (term_signal);
435 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
436 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
437 signal (SIGCHLD, SIG_DFL); /* Don't inherit CHLD handling from parent. */
439 monitored_pid = fork ();
440 if (monitored_pid == -1)
442 error (0, errno, _("fork system call failed"));
443 return EXIT_CANCELED;
445 else if (monitored_pid == 0)
446 { /* child */
447 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
448 signal (SIGTTIN, SIG_DFL);
449 signal (SIGTTOU, SIG_DFL);
451 execvp (argv[0], argv); /* FIXME: should we use "sh -c" ... here? */
453 /* exit like sh, env, nohup, ... */
454 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
455 error (0, errno, _("failed to run command %s"), quote (argv[0]));
456 return exit_status;
458 else
460 pid_t wait_result;
461 int status;
463 settimeout (timeout, true);
465 while ((wait_result = waitpid (monitored_pid, &status, 0)) < 0
466 && errno == EINTR)
467 continue;
469 if (wait_result < 0)
471 /* shouldn't happen. */
472 error (0, errno, _("error waiting for command"));
473 status = EXIT_CANCELED;
475 else
477 if (WIFEXITED (status))
478 status = WEXITSTATUS (status);
479 else if (WIFSIGNALED (status))
481 int sig = WTERMSIG (status);
482 if (WCOREDUMP (status))
483 error (0, 0, _("the monitored command dumped core"));
484 if (!timed_out && disable_core_dumps ())
486 /* exit with the signal flag set. */
487 signal (sig, SIG_DFL);
488 raise (sig);
490 status = sig + 128; /* what sh returns for signaled processes. */
492 else
494 /* shouldn't happen. */
495 error (0, 0, _("unknown status from command (%d)"), status);
496 status = EXIT_FAILURE;
500 if (timed_out && !preserve_status)
501 status = EXIT_TIMEDOUT;
502 return status;