1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2010 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
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. */
50 #include <sys/types.h>
57 #include "operand2sig.h"
62 #define PROGRAM_NAME "timeout"
64 #define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")
67 static int term_signal
= SIGTERM
; /* same default as kill command. */
68 static int monitored_pid
;
69 static int sigs_to_ignore
[NSIG
]; /* so monitor can ignore sigs it resends. */
70 static unsigned long kill_after
;
72 static struct option
const long_options
[] =
74 {"kill-after", required_argument
, NULL
, 'k'},
75 {"signal", required_argument
, NULL
, 's'},
76 {GETOPT_HELP_OPTION_DECL
},
77 {GETOPT_VERSION_OPTION_DECL
},
81 /* send sig to group but not ourselves.
82 * FIXME: Is there a better way to achieve this? */
84 send_sig (int where
, int sig
)
86 sigs_to_ignore
[sig
] = 1;
87 return kill (where
, sig
);
100 if (sigs_to_ignore
[sig
])
102 sigs_to_ignore
[sig
] = 0;
107 /* Start a new timeout after which we'll send SIGKILL. */
108 term_signal
= SIGKILL
;
110 kill_after
= 0; /* Don't let later signals reset kill alarm. */
113 if (sig
!= SIGKILL
&& sig
!= SIGCONT
)
114 send_sig (0, SIGCONT
);
116 else /* we're the child or the child is not exec'd yet. */
123 if (status
!= EXIT_SUCCESS
)
124 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
129 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
130 or: %s [OPTION]\n"), program_name
, program_name
);
133 Start COMMAND, and kill it if still running after DURATION.\n\
135 Mandatory arguments to long options are mandatory for short options too.\n\
138 -k, --kill-after=DURATION\n\
139 also send a KILL signal if COMMAND is still running\n\
140 this long after the initial signal was sent.\n\
141 -s, --signal=SIGNAL\n\
142 specify the signal to be sent on timeout.\n\
143 SIGNAL may be a name like `HUP' or a number.\n\
144 See `kill -l` for a list of signals\n"), stdout
);
146 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
147 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
150 DURATION is an integer with an optional suffix:\n\
151 `s' for seconds(the default), `m' for minutes, `h' for hours or `d' for days.\n\
155 If the command times out, then exit with status 124. Otherwise, exit\n\
156 with the status of COMMAND. If no signal is specified, send the TERM\n\
157 signal upon timeout. The TERM signal kills any process that does not\n\
158 block or catch that signal. For other processes, it may be necessary to\n\
159 use the KILL (9) signal, since this signal cannot be caught.\n"), stdout
);
160 emit_ancillary_info ();
165 /* Given a long integer value *X, and a suffix character, SUFFIX_CHAR,
166 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
167 be the NUL byte or `s' to denote seconds, `m' for minutes, `h' for
168 hours, or `d' for days. If SUFFIX_CHAR is invalid, don't modify *X
169 and return false. If *X would overflow an integer, don't modify *X
170 and return false. Otherwise return true. */
173 apply_time_suffix (unsigned long *x
, char suffix_char
)
175 unsigned int multiplier
= 1;
187 if (multiplier
> UINT_MAX
/ 60) /* 16 bit overflow */
195 if (*x
> UINT_MAX
/ multiplier
)
204 parse_duration (const char* str
)
206 unsigned long duration
;
209 if (xstrtoul (str
, &ep
, 10, &duration
, NULL
)
210 /* Invalid interval. Note 0 disables timeout */
211 || (duration
> UINT_MAX
)
212 /* Extra chars after the number and an optional s,m,h,d char. */
213 || (*ep
&& *(ep
+ 1))
214 /* Check any suffix char and update timeout based on the suffix. */
215 || !apply_time_suffix (&duration
, *ep
))
217 error (0, 0, _("invalid time interval %s"), quote (str
));
218 usage (EXIT_CANCELED
);
225 install_signal_handlers (int sigterm
)
228 sigemptyset (&sa
.sa_mask
); /* Allow concurrent calls to handler */
229 sa
.sa_handler
= cleanup
;
230 sa
.sa_flags
= SA_RESTART
; /* restart syscalls (like wait() below) */
232 sigaction (SIGALRM
, &sa
, NULL
); /* our timeout. */
233 sigaction (SIGINT
, &sa
, NULL
); /* Ctrl-C at terminal for example. */
234 sigaction (SIGQUIT
, &sa
, NULL
); /* Ctrl-\ at terminal for example. */
235 sigaction (SIGHUP
, &sa
, NULL
); /* terminal closed for example. */
236 sigaction (SIGTERM
, &sa
, NULL
); /* if we're killed, stop monitored proc. */
237 sigaction (sigterm
, &sa
, NULL
); /* user specified termination signal. */
241 main (int argc
, char **argv
)
243 unsigned long timeout
;
244 char signame
[SIG2STR_MAX
];
247 initialize_main (&argc
, &argv
);
248 set_program_name (argv
[0]);
249 setlocale (LC_ALL
, "");
250 bindtextdomain (PACKAGE
, LOCALEDIR
);
251 textdomain (PACKAGE
);
253 initialize_exit_failure (EXIT_CANCELED
);
254 atexit (close_stdout
);
256 while ((c
= getopt_long (argc
, argv
, "+k:s:", long_options
, NULL
)) != -1)
261 kill_after
= parse_duration (optarg
);
265 term_signal
= operand2sig (optarg
, signame
);
266 if (term_signal
== -1)
267 usage (EXIT_CANCELED
);
270 case_GETOPT_HELP_CHAR
;
272 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
275 usage (EXIT_CANCELED
);
280 if (argc
- optind
< 2)
281 usage (EXIT_CANCELED
);
283 timeout
= parse_duration (argv
[optind
++]);
287 /* Ensure we're in our own group so all subprocesses can be killed.
288 Note we don't just put the child in a separate group as
289 then we would need to worry about foreground and background groups
290 and propagating signals between them. */
293 /* Setup handlers before fork() so that we
294 handle any signals caused by child, without races. */
295 install_signal_handlers (term_signal
);
296 signal (SIGTTIN
, SIG_IGN
); /* don't sTop if background child needs tty. */
297 signal (SIGTTOU
, SIG_IGN
); /* don't sTop if background child needs tty. */
298 signal (SIGCHLD
, SIG_DFL
); /* Don't inherit CHLD handling from parent. */
300 monitored_pid
= fork ();
301 if (monitored_pid
== -1)
303 error (0, errno
, _("fork system call failed"));
304 return EXIT_CANCELED
;
306 else if (monitored_pid
== 0)
310 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
311 signal (SIGTTIN
, SIG_DFL
);
312 signal (SIGTTOU
, SIG_DFL
);
314 execvp (argv
[0], argv
); /* FIXME: should we use "sh -c" ... here? */
316 /* exit like sh, env, nohup, ... */
317 exit_status
= (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
318 error (0, errno
, _("failed to run command %s"), quote (argv
[0]));
327 /* We're just waiting for a single process here, so wait() suffices.
328 Note the signal() calls above on GNU/Linux and BSD at least,
329 essentially call the lower level sigaction() with the SA_RESTART flag
330 set, which ensures the following wait call will only return if the
331 child exits, not on this process receiving a signal. Also we're not
332 passing WUNTRACED | WCONTINUED to a waitpid() call and so will not get
333 indication that the child has stopped or continued. */
334 if (wait (&status
) == -1)
336 /* shouldn't happen. */
337 error (0, errno
, _("error waiting for command"));
338 status
= EXIT_CANCELED
;
342 if (WIFEXITED (status
))
343 status
= WEXITSTATUS (status
);
344 else if (WIFSIGNALED (status
))
345 status
= WTERMSIG (status
) + 128; /* what sh does at least. */
348 /* shouldn't happen. */
349 error (0, 0, _("unknown status from command (0x%X)"), status
);
350 status
= EXIT_FAILURE
;
355 return EXIT_TIMEDOUT
;