home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 1 / 1662 < prev    next >
Internet Message Format  |  1990-12-28  |  2KB

  1. From: tchrist@convex.COM (Tom Christiansen)
  2. Newsgroups: comp.unix.questions,alt.sources
  3. Subject: Re: Timeout on shell command.
  4. Message-ID: <104854@convex.convex.com>
  5. Date: 12 Aug 90 01:24:12 GMT
  6.  
  7. In article <BRISTER.90Aug10222433@westworld.decwrl.dec.com> brister@decwrl.dec.com (James Brister) writes:
  8. >I'd like to have a shell script run a command, but if that command doesn't
  9. >finish in X seconds, then the script should kill it, if the command
  10. >finishes sooner then the script should immediately continue. Any ideas on
  11. >how one could achieve this?
  12.  
  13. Here's timeout.c; syntax is 'timeout seconds command'.  
  14.  
  15. --tom
  16.  
  17. #include <stdio.h>
  18. #include <signal.h>
  19. #include <sysexits.h>
  20. #include <sys/wait.h>
  21.  
  22. int pid,count;
  23. union wait status;
  24. int bang();
  25. char **commands;
  26.  
  27. main(ac,av) 
  28.     char **av;
  29. {
  30.     if (ac < 3) {
  31. usage:  fprintf (stderr, "usage: %s seconds command\n",*av);
  32.     exit (EX_USAGE);
  33.     } 
  34.     if ((count=atoi(av[1])) < 1) {
  35.     fprintf (stderr, "seconds (%s) malformed or nonpositive\n",av[1]);
  36.     goto usage;
  37.     } 
  38.  
  39.     commands = &av[2];
  40.     switch (pid=fork()) {
  41.     default: parent(); 
  42.          /* NOTREACHED */
  43.          break;
  44.     case 0: child();  
  45.          /* NOTREACHED */
  46.     case -1: perror("fork"); 
  47.          exit(EX_OSERR); 
  48.          /* NOTREACHED */
  49.     } 
  50.  
  51. parent() {
  52.     (void) signal(SIGALRM,bang);
  53.     alarm(count);
  54.     while(wait(&status) != pid) 
  55.       /* VOID */; 
  56.     if (WIFSIGNALED(status)) 
  57.     exit(-status.w_termsig);
  58.     exit(status.w_retcode);
  59.  
  60.  
  61.  
  62. bang() {
  63.     fprintf(stderr,"Timeout!\n");
  64.     (void) signal(SIGALRM,SIG_DFL);
  65.     (void) kill(pid,SIGTERM);
  66.     if (kill(pid,0)) {
  67.     sleep(1);
  68.     (void) kill(pid,SIGKILL);
  69.     }
  70.     exit(EX_TEMPFAIL);
  71.  
  72. child() {
  73.     execvp(*commands,commands);
  74.     perror(*commands);
  75.     _exit(EX_DATAERR);
  76.     /* NOTREACHED */
  77.  
  78. /* lint output:
  79.  *    timeout.c:
  80.  */
  81. --
  82.  
  83.     Tom Christiansen                       {uunet,uiucdcs,sun}!convex!tchrist 
  84.     Convex Computer Corporation                            tchrist@convex.COM
  85.          "EMACS belongs in <sys/errno.h>: Editor too big!"
  86.