1 /* timeout.c - Run command line with a timeout
2 *
3 * Copyright 2013 Rob Landley <rob@landley.net>
4 *
5 * No standard
6
7 USE_TIMEOUT(NEWTOY(timeout, "<2^(foreground)(preserve-status)vk:s(signal):", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_ARGFAIL(125)))
8
9 config TIMEOUT
10 bool "timeout"
11 default y
12 help
13 usage: timeout [-k DURATION] [-s SIGNAL] DURATION COMMAND...
14
15 Run command line as a child process, sending child a signal if the
16 command doesn't exit soon enough.
17
18 DURATION can be a decimal fraction. An optional suffix can be "m"
19 (minutes), "h" (hours), "d" (days), or "s" (seconds, the default).
20
21 -s Send specified signal (default TERM)
22 -k Send KILL signal if child still running this long after first signal
23 -v Verbose
24 --foreground Don't create new process group
25 --preserve-status Exit with the child's exit status
26 */
27
28 #define FOR_timeout
29 #include "toys.h"
30
31 GLOBALS(
32 char *s, *k;
33
34 int nextsig;
35 pid_t pid;
36 struct timespec kts;
37 struct itimerspec its;
38 timer_t timer;
39 )
40
handler(int i)41 static void handler(int i)
42 {
43 if (FLAG(v))
44 fprintf(stderr, "timeout pid %d signal %d\n", TT.pid, TT.nextsig);
45
46 toys.exitval = (TT.nextsig==9) ? 137 : 124;
47 kill(TT.pid, TT.nextsig);
48 if (TT.k) {
49 TT.k = 0;
50 TT.nextsig = SIGKILL;
51 xsignal(SIGALRM, handler);
52 TT.its.it_value = TT.kts;
53 if (timer_settime(TT.timer, 0, &TT.its, 0)) perror_exit("timer_settime");
54 }
55 }
56
timeout_main(void)57 void timeout_main(void)
58 {
59 struct sigevent se = { .sigev_notify = SIGEV_SIGNAL, .sigev_signo = SIGALRM };
60
61 // Use same ARGFAIL value for any remaining parsing errors
62 toys.exitval = 125;
63 xparsetimespec(*toys.optargs, &TT.its.it_value);
64 if (TT.k) xparsetimespec(TT.k, &TT.kts);
65
66 TT.nextsig = SIGTERM;
67 if (TT.s && -1 == (TT.nextsig = sig_to_num(TT.s)))
68 error_exit("bad -s: '%s'", TT.s);
69
70 if (!FLAG(foreground)) setpgid(0, 0);
71
72 toys.exitval = 0;
73 if (!(TT.pid = XVFORK())) xexec(toys.optargs+1);
74 else {
75 int status;
76
77 xsignal(SIGALRM, handler);
78 if (timer_create(CLOCK_MONOTONIC, &se, &TT.timer)) perror_exit("timer");
79 if (timer_settime(TT.timer, 0, &TT.its, 0)) perror_exit("timer_settime");
80
81 status = xwaitpid(TT.pid);
82 if (FLAG(preserve_status) || !toys.exitval) toys.exitval = status;
83 }
84 }
85