Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Running a command and stopping it after x seconds - how

Options
  • 02-04-2008 10:42am
    #1
    Registered Users Posts: 5,580 ✭✭✭


    I am doing a script that runs a command. This command will run indefinitely.

    Is there a way of scripting it to only run for say, 5 minutes and then quit out?


Comments

  • Registered Users Posts: 5,580 ✭✭✭veryangryman


    Shell scripting (Unix)


  • Registered Users Posts: 23,212 ✭✭✭✭Tom Dunne


    There is.

    Get the start time, set up a loop, end when the start time=start time+5 minutes.

    Post up what you have and we will see if we can help.


  • Registered Users Posts: 1,922 ✭✭✭fergalr


    You are looking for a way of killing a process that you earlier created in your script?

    There are many ways of doing this, but what exactly you do depends on what environment/language/OS you are using.

    Generically, I think you should be trying to spawn (fork and then exec) the command process, capture it's PID, sleep the parent for however long you want, wake, kill child process.

    Sort of like:

    if (!(childID = fork)) {
    exec ("command");
    }
    sleep(length of time);
    kill childID;
    exit()

    (note, this assumes the child process doesn't terminate prematurely)


  • Subscribers Posts: 4,076 ✭✭✭IRLConor


    Run this script:
    #!/bin/sh
    
    DELAY=$1
    SIGNAL=$2
    shift 2
    
    $@ &
    CHILD_PID=$!
    
    sleep ${DELAY}
    kill -${SIGNAL} ${CHILD_PID}
    

    like so:
    $ sh runfor.sh 10 INT ping 127.0.0.1
    

    In other words, the first argument to the script is the amount of time in seconds, the second argument is the signal to send the process when the time is up and the remaining arguments are the command.


Advertisement