+/* -*-c-*-
+ *
+ * Run a command with a timeout.
+ *
+ * (c) 2011 Mark Wooding
+ */
+
+/*----- Licensing notice --------------------------------------------------*
+ *
+ * This file is part of the Toys utilties collection.
+ *
+ * Toys is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Toys is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Toys; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+/*----- Basic strategy ----------------------------------------------------*
+ *
+ * There's an obvious and simple way to make a process stop after a certain
+ * amount of time: set an alarm. Alarms are inherited, so this will take
+ * down the whole subprocess tree. Unfortunately, processes use alarms for
+ * all sorts of things. And this relies on the process not fiddling with its
+ * @SIGALRM@ handler.
+ *
+ * The other possibility is to have a separate process which kills our target
+ * program when the time's up. In order to do this effectively, we need to
+ * trap the whole thing in a process group. Then we need to wait until the
+ * time is up or the process finished. We'll assume that the top-level
+ * process finishing is sufficient indication that we don't need to hang on
+ * any longer.
+ *
+ * This isn't perfect. It won't catch stragglers if the target process
+ * creates its own sub-process groups -- so, in particular, nested timeouts
+ * won't behave in an obvious way. And, possibly most annoyingly, it
+ * interferes with the way terminal I/O works. I'm sorry: you can't have
+ * everything.
+ */
+
+/*----- Header files ------------------------------------------------------*/
+
+#include <ctype.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/select.h>
+#include <sys/wait.h>
+
+#include <mLib/fdflags.h>
+#include <mLib/macros.h>
+#include <mLib/mdwopt.h>
+#include <mLib/quis.h>
+#include <mLib/report.h>
+#include <mLib/sel.h>
+#include <mLib/sig.h>
+#include <mLib/tv.h>
+
+/*----- Static variables --------------------------------------------------*/
+
+static sel_state sel;
+static int state;
+
+enum {
+ ST_WAIT,
+ ST_ABORT,
+ ST_DONE
+};
+
+/*----- Argument conversion functions -------------------------------------*/
+
+/* --- @namesig@ --- *
+ *
+ * Arguments: @const char *p@ = pointer to string
+ *
+ * Returns: Signal number, or @-1@ for no match.
+ *
+ * Use: Converts a signal name into its number.
+ */
+
+struct namesig {
+ const char *name;
+ int sig;
+};
+
+int cmp_namesig(const void *k, const void *v)
+ { const struct namesig *ns = v; return (strcmp(k, ns->name)); }
+
+static int namesig(const char *p)
+{
+ const static struct namesig tab[] = {
+/*
+ ;;; The signal name table is very boring to type. To make life less awful,
+ ;;; put the signal names in this list and evaluate the code to get Emacs to
+ ;;; regenerate it. We use @bsearch@ on it, so it's important that it be
+ ;;; sorted: Emacs does this for us.
+ (let ((signals '(HUP INT QUIT ILL ABRT FPE KILL SEGV PIPE ALRM TERM
+ USR1 USR2 CHLD CONT STOP TSTP TTIN TTOU BUS POLL
+ PROF SYS TRAP URG VTALRM XCPU XFSZ IOT EMT STKFLT
+ IO CLD PWR INFO LOST WINCH)))
+ (save-excursion
+ (goto-char (point-min))
+ (let ((start (search-forward (concat "/" "* SIGLIST *" "/\n")))
+ (end (search-forward (concat "/" "* END *" "/\n"))))
+ (delete-region start end))
+ (dolist (sig (sort (copy-list signals) #'string<))
+ (insert (format "#ifdef SIG%s\n { \"%s\", SIG%s },\n#endif\n"
+ sig sig sig)))
+ (insert (concat "/" "* END *" "/\n"))))
+*/
+
+/* SIGLIST */
+#ifdef SIGABRT
+ { "ABRT", SIGABRT },
+#endif
+#ifdef SIGALRM
+ { "ALRM", SIGALRM },
+#endif
+#ifdef SIGBUS
+ { "BUS", SIGBUS },
+#endif
+#ifdef SIGCHLD
+ { "CHLD", SIGCHLD },
+#endif
+#ifdef SIGCLD
+ { "CLD", SIGCLD },
+#endif
+#ifdef SIGCONT
+ { "CONT", SIGCONT },
+#endif
+#ifdef SIGEMT
+ { "EMT", SIGEMT },
+#endif
+#ifdef SIGFPE
+ { "FPE", SIGFPE },
+#endif
+#ifdef SIGHUP
+ { "HUP", SIGHUP },
+#endif
+#ifdef SIGILL
+ { "ILL", SIGILL },
+#endif
+#ifdef SIGINFO
+ { "INFO", SIGINFO },
+#endif
+#ifdef SIGINT
+ { "INT", SIGINT },
+#endif
+#ifdef SIGIO
+ { "IO", SIGIO },
+#endif
+#ifdef SIGIOT
+ { "IOT", SIGIOT },
+#endif
+#ifdef SIGKILL
+ { "KILL", SIGKILL },
+#endif
+#ifdef SIGLOST
+ { "LOST", SIGLOST },
+#endif
+#ifdef SIGPIPE
+ { "PIPE", SIGPIPE },
+#endif
+#ifdef SIGPOLL
+ { "POLL", SIGPOLL },
+#endif
+#ifdef SIGPROF
+ { "PROF", SIGPROF },
+#endif
+#ifdef SIGPWR
+ { "PWR", SIGPWR },
+#endif
+#ifdef SIGQUIT
+ { "QUIT", SIGQUIT },
+#endif
+#ifdef SIGSEGV
+ { "SEGV", SIGSEGV },
+#endif
+#ifdef SIGSTKFLT
+ { "STKFLT", SIGSTKFLT },
+#endif
+#ifdef SIGSTOP
+ { "STOP", SIGSTOP },
+#endif
+#ifdef SIGSYS
+ { "SYS", SIGSYS },
+#endif
+#ifdef SIGTERM
+ { "TERM", SIGTERM },
+#endif
+#ifdef SIGTRAP
+ { "TRAP", SIGTRAP },
+#endif
+#ifdef SIGTSTP
+ { "TSTP", SIGTSTP },
+#endif
+#ifdef SIGTTIN
+ { "TTIN", SIGTTIN },
+#endif
+#ifdef SIGTTOU
+ { "TTOU", SIGTTOU },
+#endif
+#ifdef SIGURG
+ { "URG", SIGURG },
+#endif
+#ifdef SIGUSR1
+ { "USR1", SIGUSR1 },
+#endif
+#ifdef SIGUSR2
+ { "USR2", SIGUSR2 },
+#endif
+#ifdef SIGVTALRM
+ { "VTALRM", SIGVTALRM },
+#endif
+#ifdef SIGWINCH
+ { "WINCH", SIGWINCH },
+#endif
+#ifdef SIGXCPU
+ { "XCPU", SIGXCPU },
+#endif
+#ifdef SIGXFSZ
+ { "XFSZ", SIGXFSZ },
+#endif
+/* END */
+ };
+
+ const struct namesig *ns = bsearch(p, tab, N(tab), sizeof(tab[0]),
+ cmp_namesig);
+ if (ns) return (ns->sig);
+ else if (isdigit((unsigned char)*p)) return (atoi(p));
+ else return (-1);
+}
+
+/*----- Help functions ----------------------------------------------------*/
+
+static void usage(FILE *fp)
+ { pquis(fp, "Usage: $ [-s SIG] SECONDS COMMAND [ARGUMENTS ...]\n"); }
+
+static void version(FILE *fp)
+ { pquis(fp, "$ (version " VERSION ")\n"); }
+
+static void help(FILE *fp)
+{
+ version(fp); fputc('\n', stdout);
+ usage(fp);
+ pquis(fp, "\n\
+Run COMMAND, giving it the ARGUMENTS. If it fails to complete within the\n\
+specified number of SECONDS, kill it. Otherwise exit with the status it\n\
+returns.\n \
+\n\
+Options:\n\
+ -h, --help Show this help text.\n\
+ -v, --version Show version string.\n\
+ -u, --usage Show a terse usage summary.\n\
+\n\
+ -s, --signal=SIG Send signal SIG to the command.\n\
+");
+}
+
+/*----- Timeout handling --------------------------------------------------*/
+
+/* --- @timeout@ --- *
+ *
+ * The first time, we send the signal requested by the caller. Then we wait
+ * five seconds for the child to die, and send @SIGKILL@. If that still
+ * doesn't help, then we just give up. It's not like there's anything else
+ * we can do which is likely to help. And it's not like the process is going
+ * to be doing anything else in user mode ever again.
+ */
+
+struct timeout {
+ sel_timer t;
+ int panic;
+ int sig;
+ pid_t kid;
+};
+
+static void timeout(struct timeval *now, void *p)
+{
+ struct timeout *t = p;
+ struct timeval tv;
+
+ switch (t->panic) {
+ case 0:
+ moan("timed out: killing child process");
+ kill(-t->kid, t->sig);
+ break;
+ case 1:
+ moan("child hasn't responded: killing harder");
+ kill(-t->kid, SIGKILL);
+ break;
+ case 2:
+ moan("child still undead: giving up");
+ state = ST_ABORT;
+ break;
+ }
+ TV_ADDL(&tv, now, 5, 0);
+ sel_addtimer(&sel, &t->t, &tv, timeout, t);
+ t->panic++;
+}
+
+/*----- Signal handling ---------------------------------------------------*/
+
+/* --- @sigchld@ --- *
+ *
+ * If it's our child that died, fetch its exit status and stop.
+ */
+
+struct sigchld {
+ pid_t kid;
+ int rc;
+};
+
+static void sigchld(int sig, void *p)
+{
+ struct sigchld *s = p;
+ int rc;
+ pid_t pid;
+
+ if ((pid = waitpid(s->kid, &rc, WNOHANG)) < 0)
+ die(254, "waitpid failed: %s", strerror(errno));
+ if (pid == s->kid) {
+ s->rc = rc;
+ state = ST_DONE;
+ }
+}
+
+/* --- @sigpropagate@ --- *
+ *
+ * Propagate various signals to the child process group and then maybe act on
+ * them.
+ */
+
+static void sigpropagate(int sig, void *p)
+{
+ struct sigchld *s = p;
+
+ kill(-s->kid, sig);
+ switch (sig) {
+ case SIGTSTP: raise(SIGSTOP); break;
+ }
+}
+
+#define PROPAGATE_SIGNALS(_) \
+ _(TSTP) _(CONT) _(INT) _(HUP) _(QUIT)
+
+/*----- Main program ------------------------------------------------------*/
+
+/* --- @main@ --- */
+
+int main(int argc, char *const argv[])
+{
+ char *p;
+ double t;
+ int signo = SIGTERM;
+ pid_t kid;
+ struct timeval tv;
+ struct timeout to;
+ struct sigchld sc;
+ sig sig_CHLD;
+#define DEFSIG(tag) sig sig_##tag;
+ PROPAGATE_SIGNALS(DEFSIG)
+#undef DEFSIG
+ unsigned f = 0;
+#define F_BOGUS 1u
+
+ /* --- Option parsing --- */
+
+ ego(argv[0]);
+
+ for (;;) {
+ static const struct option opts[] = {
+ { "help", 0, 0, 'h' },
+ { "version", 0, 0, 'v' },
+ { "usage", 0, 0, 'u' },
+ { "signal", OPTF_ARGREQ, 0, 's' },
+ { 0, 0, 0, 0 }
+ };
+
+ int i = mdwopt(argc, argv, "+hvus:", opts, 0, 0, 0);
+ if (i < 0) break;
+ switch (i) {
+ case 'h': help(stdout); exit(0);
+ case 'v': version(stdout); exit(0);
+ case 'u': usage(stdout); exit(0);
+ case 's':
+ if ((signo = namesig(optarg)) < 0)
+ die(253, "bad signal spec `%s'", optarg);
+ break;
+ default: f |= F_BOGUS; break;
+ }
+ }
+ argc -= optind; argv += optind;
+ if ((f & F_BOGUS) || argc < 2) { usage(stderr); exit(253); }
+
+ p = argv[0];
+ while (isspace((unsigned char)*p)) p++;
+ t = strtod(argv[0], &p);
+ while (isspace((unsigned char)*p)) p++;
+ if (*p) die(254, "bad time value `%s'", argv[0]);
+
+ /* --- Get things set up --- */
+
+ state = ST_WAIT;
+ sel_init(&sel);
+
+ /* --- Set up signal handling --- *
+ *
+ * Doing anything with asynchronous signals is a mug's game, so we bring
+ * them in-band. Do this before starting the child process, because
+ * otherwise we might miss an immediate @SIGCHLD@.
+ */
+
+ sig_init(&sel);
+ sc.rc = 0;
+ sig_add(&sig_CHLD, SIGCHLD, sigchld, &sc);
+#define ADDSIG(tag) sig_add(&sig_##tag, SIG##tag, sigpropagate, &sc);
+ PROPAGATE_SIGNALS(ADDSIG)
+#undef ADDSIG
+
+ /* --- Now start the child process --- */
+
+ if ((kid = fork()) < 0) die(2, "fork failed: %s", strerror(errno));
+ if (!kid) {
+ setpgid(0, 0);
+ execvp(argv[1], argv + 1);
+ _exit(252);
+ }
+ sc.kid = kid;
+
+ /* --- Set up the timer --- */
+
+ to.kid = kid;
+ to.sig = signo;
+ to.panic = 0;
+ gettimeofday(&tv, 0);
+ TV_ADDL(&tv, &tv, (time_t)t, ((long)(t * 1000000))%1000000);
+ sel_addtimer(&sel, &to.t, &tv, timeout, &to);
+
+ /* --- Main @select@ loop */
+
+ while (state == ST_WAIT) {
+ if (sel_select(&sel)) {
+ if (errno == EINTR) continue;
+ die(254, "select failed: %s", strerror(errno));
+ }
+ }
+
+ /* --- Check and translate the exit code --- */
+
+ switch (state) {
+ case ST_ABORT:
+ exit(251);
+ case ST_DONE:
+ if (WIFEXITED(sc.rc))
+ exit(WEXITSTATUS(sc.rc));
+ else if (WIFSIGNALED(sc.rc))
+ exit(128 | WTERMSIG(sc.rc));
+ else
+ exit(128);
+ default:
+ moan("FATAL: unexpected state %d", state);
+ abort();
+ }
+}
+
+/*----- That's all, folks -------------------------------------------------*/