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?
1 Answers
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
sfor seconds ,mfor minutes ,hfor hours ,dfor 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 arg2NOTE: Default timeout signal isSIGTERMfor which some processes does not terminate. In that case we need to useSIGKILLsignal to kill the process.timeout -s KILL 2m /path/to/script arg1 arg2OR
timeout -k 30 2m /path/to/slow-command arg1 arg2In this case, timeout first sends the
SIGTERMsignal after initial timeout of 2 minutes. Then, waits for another timeout of 30 seconds and sends aSIGKILLto 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 :
Condition
sleepthenkill:/path/to/script arg1 arg2 & sleep 2m ; kill $!Perl Alarms (This can be used within a sequential script.) :
perl -e "alarm 120; exec @ARGV" "/path/to/script arg1 arg2"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.
- 2,730