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 Answer
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 isSIGTERM
for which some processes does not terminate. In that case we need to useSIGKILL
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 aSIGKILL
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 :
Condition
sleep
thenkill
:/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.