Timeout on shell command.

Tom Christiansen tchrist at convex.COM
Sun Aug 12 11:24:12 AEST 1990


In article <BRISTER.90Aug10222433 at westworld.decwrl.dec.com> brister at 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 <stdio.h>
#include <signal.h>
#include <sysexits.h>
#include <sys/wait.h>

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 at convex.COM
		 "EMACS belongs in <sys/errno.h>: Editor too big!"



More information about the Comp.unix.questions mailing list