Xref: utzoo comp.unix.questions:24564 alt.sources:2157 Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!convex!convex.COM From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.unix.questions,alt.sources Subject: Re: Timeout on shell command. Message-ID: <104854@convex.convex.com> Date: 12 Aug 90 01:24:12 GMT References: Sender: news@convex.com Reply-To: tchrist@convex.COM (Tom Christiansen) Followup-To: comp.unix.questions Organization: CONVEX Software Development, Richardson, TX Lines: 83 In article brister@decwrl.dec.com (James Brister) writes: >I'd like to have a shell script run a command, but if that command doesn't >finish in X seconds, then the script should kill it, if the command >finishes sooner then the script should immediately continue. Any ideas on >how one could achieve this? Here's timeout.c; syntax is 'timeout seconds command'. --tom #include #include #include #include int pid,count; union wait status; int bang(); char **commands; main(ac,av) char **av; { if (ac < 3) { usage: fprintf (stderr, "usage: %s seconds command\n",*av); exit (EX_USAGE); } if ((count=atoi(av[1])) < 1) { fprintf (stderr, "seconds (%s) malformed or nonpositive\n",av[1]); goto usage; } commands = &av[2]; switch (pid=fork()) { default: parent(); /* NOTREACHED */ break; case 0: child(); /* NOTREACHED */ case -1: perror("fork"); exit(EX_OSERR); /* NOTREACHED */ } } parent() { (void) signal(SIGALRM,bang); alarm(count); while(wait(&status) != pid) /* VOID */; if (WIFSIGNALED(status)) exit(-status.w_termsig); exit(status.w_retcode); } bang() { fprintf(stderr,"Timeout!\n"); (void) signal(SIGALRM,SIG_DFL); (void) kill(pid,SIGTERM); if (kill(pid,0)) { sleep(1); (void) kill(pid,SIGKILL); } exit(EX_TEMPFAIL); } child() { execvp(*commands,commands); perror(*commands); _exit(EX_DATAERR); /* NOTREACHED */ } /* lint output: * timeout.c: */ -- Tom Christiansen {uunet,uiucdcs,sun}!convex!tchrist Convex Computer Corporation tchrist@convex.COM "EMACS belongs in : Editor too big!"