tests: adjust memory limits in head-c.sh
[coreutils.git] / src / timeout.c
blob9c31df529c36bbf4f001cdbeebb3af1457b852bf
1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2016 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);
207 /* The normal case is the job has remained in our
208 newly created process group, so send to all processes in that. */
209 if (!foreground)
211 send_sig (0, sig);
212 if (sig != SIGKILL && sig != SIGCONT)
214 send_sig (monitored_pid, SIGCONT);
215 send_sig (0, SIGCONT);
219 else /* we're the child or the child is not exec'd yet. */
220 _exit (128 + sig);
223 void
224 usage (int status)
226 if (status != EXIT_SUCCESS)
227 emit_try_help ();
228 else
230 printf (_("\
231 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
232 or: %s [OPTION]\n"), program_name, program_name);
234 fputs (_("\
235 Start COMMAND, and kill it if still running after DURATION.\n\
236 "), stdout);
238 emit_mandatory_arg_note ();
240 fputs (_("\
241 --preserve-status\n\
242 exit with the same status as COMMAND, even when the\n\
243 command times out\n\
244 --foreground\n\
245 when not running timeout directly from a shell prompt,\n\
246 allow COMMAND to read from the TTY and get TTY signals;\n\
247 in this mode, children of COMMAND will not be timed out\n\
248 -k, --kill-after=DURATION\n\
249 also send a KILL signal if COMMAND is still running\n\
250 this long after the initial signal was sent\n\
251 -s, --signal=SIGNAL\n\
252 specify the signal to be sent on timeout;\n\
253 SIGNAL may be a name like 'HUP' or a number;\n\
254 see 'kill -l' for a list of signals\n"), stdout);
256 fputs (HELP_OPTION_DESCRIPTION, stdout);
257 fputs (VERSION_OPTION_DESCRIPTION, stdout);
259 fputs (_("\n\
260 DURATION is a floating point number with an optional suffix:\n\
261 's' for seconds (the default), 'm' for minutes, 'h' for hours \
262 or 'd' for days.\n"), stdout);
264 fputs (_("\n\
265 If the command times out, and --preserve-status is not set, then exit with\n\
266 status 124. Otherwise, exit with the status of COMMAND. If no signal\n\
267 is specified, send the TERM signal upon timeout. The TERM signal kills\n\
268 any process that does not block or catch that signal. It may be necessary\n\
269 to use the KILL (9) signal, since this signal cannot be caught, in which\n\
270 case the exit status is 128+9 rather than 124.\n"), stdout);
271 emit_ancillary_info (PROGRAM_NAME);
273 exit (status);
276 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
277 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
278 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
279 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
280 and return false. Otherwise return true. */
282 static bool
283 apply_time_suffix (double *x, char suffix_char)
285 int multiplier;
287 switch (suffix_char)
289 case 0:
290 case 's':
291 multiplier = 1;
292 break;
293 case 'm':
294 multiplier = 60;
295 break;
296 case 'h':
297 multiplier = 60 * 60;
298 break;
299 case 'd':
300 multiplier = 60 * 60 * 24;
301 break;
302 default:
303 return false;
306 *x *= multiplier;
308 return true;
311 static double
312 parse_duration (const char* str)
314 double duration;
315 const char *ep;
317 if (!xstrtod (str, &ep, &duration, c_strtod)
318 /* Nonnegative interval. */
319 || ! (0 <= duration)
320 /* No extra chars after the number and an optional s,m,h,d char. */
321 || (*ep && *(ep + 1))
322 /* Check any suffix char and update timeout based on the suffix. */
323 || !apply_time_suffix (&duration, *ep))
325 error (0, 0, _("invalid time interval %s"), quote (str));
326 usage (EXIT_CANCELED);
329 return duration;
332 static void
333 install_signal_handlers (int sigterm)
335 struct sigaction sa;
336 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
337 sa.sa_handler = cleanup;
338 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
339 more likely to work cleanly. */
341 sigaction (SIGALRM, &sa, NULL); /* our timeout. */
342 sigaction (SIGINT, &sa, NULL); /* Ctrl-C at terminal for example. */
343 sigaction (SIGQUIT, &sa, NULL); /* Ctrl-\ at terminal for example. */
344 sigaction (SIGHUP, &sa, NULL); /* terminal closed for example. */
345 sigaction (SIGTERM, &sa, NULL); /* if we're killed, stop monitored proc. */
346 sigaction (sigterm, &sa, NULL); /* user specified termination signal. */
349 /* Try to disable core dumps for this process.
350 Return TRUE if successful, FALSE otherwise. */
351 static bool
352 disable_core_dumps (void)
354 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
355 if (prctl (PR_SET_DUMPABLE, 0) == 0)
356 return true;
358 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
359 /* Note this doesn't disable processing by a filter in
360 /proc/sys/kernel/core_pattern on Linux. */
361 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0,0}) == 0)
362 return true;
364 #else
365 return false;
366 #endif
368 error (0, errno, _("warning: disabling core dumps failed"));
369 return false;
373 main (int argc, char **argv)
375 double timeout;
376 char signame[SIG2STR_MAX];
377 int c;
379 initialize_main (&argc, &argv);
380 set_program_name (argv[0]);
381 setlocale (LC_ALL, "");
382 bindtextdomain (PACKAGE, LOCALEDIR);
383 textdomain (PACKAGE);
385 initialize_exit_failure (EXIT_CANCELED);
386 atexit (close_stdout);
388 while ((c = getopt_long (argc, argv, "+k:s:", long_options, NULL)) != -1)
390 switch (c)
392 case 'k':
393 kill_after = parse_duration (optarg);
394 break;
396 case 's':
397 term_signal = operand2sig (optarg, signame);
398 if (term_signal == -1)
399 usage (EXIT_CANCELED);
400 break;
402 case FOREGROUND_OPTION:
403 foreground = true;
404 break;
406 case PRESERVE_STATUS_OPTION:
407 preserve_status = true;
408 break;
410 case_GETOPT_HELP_CHAR;
412 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
414 default:
415 usage (EXIT_CANCELED);
416 break;
420 if (argc - optind < 2)
421 usage (EXIT_CANCELED);
423 timeout = parse_duration (argv[optind++]);
425 argv += optind;
427 /* Ensure we're in our own group so all subprocesses can be killed.
428 Note we don't just put the child in a separate group as
429 then we would need to worry about foreground and background groups
430 and propagating signals between them. */
431 if (!foreground)
432 setpgid (0, 0);
434 /* Setup handlers before fork() so that we
435 handle any signals caused by child, without races. */
436 install_signal_handlers (term_signal);
437 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
438 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
439 signal (SIGCHLD, SIG_DFL); /* Don't inherit CHLD handling from parent. */
441 monitored_pid = fork ();
442 if (monitored_pid == -1)
444 error (0, errno, _("fork system call failed"));
445 return EXIT_CANCELED;
447 else if (monitored_pid == 0)
448 { /* child */
449 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
450 signal (SIGTTIN, SIG_DFL);
451 signal (SIGTTOU, SIG_DFL);
453 execvp (argv[0], argv); /* FIXME: should we use "sh -c" ... here? */
455 /* exit like sh, env, nohup, ... */
456 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
457 error (0, errno, _("failed to run command %s"), quote (argv[0]));
458 return exit_status;
460 else
462 pid_t wait_result;
463 int status;
465 settimeout (timeout, true);
467 while ((wait_result = waitpid (monitored_pid, &status, 0)) < 0
468 && errno == EINTR)
469 continue;
471 if (wait_result < 0)
473 /* shouldn't happen. */
474 error (0, errno, _("error waiting for command"));
475 status = EXIT_CANCELED;
477 else
479 if (WIFEXITED (status))
480 status = WEXITSTATUS (status);
481 else if (WIFSIGNALED (status))
483 int sig = WTERMSIG (status);
484 if (WCOREDUMP (status))
485 error (0, 0, _("the monitored command dumped core"));
486 if (!timed_out && disable_core_dumps ())
488 /* exit with the signal flag set. */
489 signal (sig, SIG_DFL);
490 raise (sig);
492 status = sig + 128; /* what sh returns for signaled processes. */
494 else
496 /* shouldn't happen. */
497 error (0, 0, _("unknown status from command (%d)"), status);
498 status = EXIT_FAILURE;
502 if (timed_out && !preserve_status)
503 status = EXIT_TIMEDOUT;
504 return status;