6

Is it possible to run a script from bash (e.g. python) with a termination time, meaning that if this script runs for longer than X seconds, terminate it?

0

1 Answer 1

5

Yes, It is possible to run a bash script with a timeout for it's termination. You can do it by :

1. Using timeout :

It runs a command with a time limit. General syntax includes :

timeout signal duration command/script arguments

where :

  • signal is Signal name or corresponding number. See man 7 signal
  • Duration is Timeout specified in numbers with suffix as s for seconds , m for minutes , h for hours , d for days.
  • Default is seconds, When you only specify just a number. As an example say you want to terminate your script after 2 minutes, then :

    timeout 2m /path/to/script arg1 arg2
    
  • NOTE : Default timeout signal is SIGTERM for which some processes does not terminate. In that case we need to use SIGKILL signal to kill the process.

        timeout -s KILL 2m /path/to/script arg1 arg2
    

    OR

        timeout -k 30 2m /path/to/slow-command arg1 arg2
    

    In this case, timeout first sends the SIGTERM signal after initial timeout of 2 minutes. Then, waits for another timeout of 30 seconds and sends a SIGKILL to the process if it’s still running.

2. I don't have timeout command :

Well, There are many alternatives or workarounds, If for some reason you are unable to use timeout. These are :

  1. Condition sleep then kill :

       /path/to/script arg1 arg2 & sleep 2m ; kill $!
    
  2. Perl Alarms (This can be used within a sequential script.) :

       perl -e "alarm 120; exec @ARGV" "/path/to/script arg1 arg2"
    
  3. Using expect command :

       time_out=120
       command="/path/to/script arg1 arg2"
    
       expect -c " set echo \"-noecho\";
                   set timeout $time_out;
                   spawn -noecho $command;
                   expect timeout { exit 1 } eof { exit 0 } "
    

Feel free to add-in more details.

Not the answer you're looking for? Browse other questions tagged .