toybox/toys/other/timeout.c
<<
>>
Prefs
   1/* timeout.c - Run command line with a timeout
   2 *
   3 * Copyright 2013 Rob Landley <rob@landley.net>
   4 *
   5 * No standard
   6
   7USE_TIMEOUT(NEWTOY(timeout, "<2^vk:s: ", TOYFLAG_USR|TOYFLAG_BIN))
   8
   9config TIMEOUT
  10  bool "timeout"
  11  default y
  12  depends on TOYBOX_FLOAT
  13  help
  14    usage: timeout [-k LENGTH] [-s SIGNAL] LENGTH COMMAND...
  15
  16    Run command line as a child process, sending child a signal if the
  17    command doesn't exit soon enough.
  18
  19    Length can be a decimal fraction. An optional suffix can be "m"
  20    (minutes), "h" (hours), "d" (days), or "s" (seconds, the default).
  21
  22    -s  Send specified signal (default TERM)
  23    -k  Send KILL signal if child still running this long after first signal
  24    -v  Verbose
  25*/
  26
  27#define FOR_timeout
  28#include "toys.h"
  29
  30GLOBALS(
  31  char *s, *k;
  32
  33  int nextsig;
  34  pid_t pid;
  35  struct timeval ktv;
  36  struct itimerval itv;
  37)
  38
  39static void handler(int i)
  40{
  41  if (toys.optflags & FLAG_v)
  42    fprintf(stderr, "timeout pid %d signal %d\n", TT.pid, TT.nextsig);
  43  kill(TT.pid, TT.nextsig);
  44  
  45  if (TT.k) {
  46    TT.k = 0;
  47    TT.nextsig = SIGKILL;
  48    xsignal(SIGALRM, handler);
  49    TT.itv.it_value = TT.ktv;
  50    setitimer(ITIMER_REAL, &TT.itv, (void *)toybuf);
  51  }
  52}
  53
  54// timeval inexplicably makes up a new type for microseconds, despite timespec's
  55// nanoseconds field (needing to store 1000* the range) using "long". Bravo.
  56void xparsetimeval(char *s, struct timeval *tv)
  57{
  58  long ll;
  59
  60  tv->tv_sec = xparsetime(s, 6, &ll);
  61  tv->tv_usec = ll;
  62}
  63
  64void timeout_main(void)
  65{
  66  // Parse early to get any errors out of the way.
  67  xparsetimeval(*toys.optargs, &TT.itv.it_value);
  68  if (TT.k) xparsetimeval(TT.k, &TT.ktv);
  69
  70  TT.nextsig = SIGTERM;
  71  if (TT.s && -1 == (TT.nextsig = sig_to_num(TT.s)))
  72    error_exit("bad -s: '%s'", TT.s);
  73
  74  if (!(TT.pid = XVFORK())) xexec(toys.optargs+1);
  75  else {
  76    xsignal(SIGALRM, handler);
  77    setitimer(ITIMER_REAL, &TT.itv, (void *)toybuf);
  78    toys.exitval = xwaitpid(TT.pid);
  79  }
  80}
  81