timeout.c 2.2 KB

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