[Ilugc] timeout in shell command

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Sun Sep 9 18:23:58 2007

On Sun, Sep 09, 2007 at 05:36:13AM -0700, Amit Dey wrote:

Assume that i have to execute a binary file 
  so i do
  ./binaryfilename
  Now there is a chance that the execution may run into an infinite loop.
   
  What i want is that if the execution has not completed in 10 seconds then 
it should be aborted and i should get some kind of signal for incomplete 
execution.
   
  any suggestions?


Long ago I had written a program called killmyself.c that I have
attached here.

It is not great code but gets the job done.

If you want to generate a signal use kill(2).

Best,
Girish

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>

extern char *__progname;

/* This program self destructs after a specified time */
int main(int argc, char **argv) {

        int ret;
        long minutes;
        struct timeval t, t2;
        pid_t child;
        if (argc < 3) {
                printf("Usage: %s <minutes> <mplayer arguments> \n",
                                __progname);
                exit(128);
                /* NOT REACHED */
        }


        if ( (child =  fork()) != 0) {
                /* I am the parent process */
                minutes = strtol(argv[1], NULL, 10);
                sleep(60 * minutes);


                /* I am done! */
                kill(child, SIGINT);
                exit(0);

        } else {
                /* I am the child */
                execv("/usr/local/bin/mplayer", argv + 1);
                                
                exit(0);
        }
}

Other related posts: