Objective: Execute / Run a command and kill it if it’s still running after a specified duration on Unix / Linux.
On Linux, the
timeout utility can be used to run a command with a time limit. The timeout command will kill the process once the specified duration has elapsed. The duration is a number with an optional suffix: ‘s’ for seconds (the default), ‘m’ for minutes, ‘h’ for hours or ‘d’ for days.
To kill a slow process after 1 minute, you can use the following syntax.
$ timeout 60 /path/to/slow-command arg1 arg2
The duration can also be specified in minutes using the following syntax.
$ timeout 1m /path/to/slow-command arg1 arg2
The arguments “arg1” and “arg2” are passed as input to
slow-command and not to the
timeout utility. After 1 minute, the timeout sends a
SIGTERM signal to the process. Some process will not terminate when a
SIGTERM signal is sent. In such cases, we will need to send a
SIGKILL signal to the process instead.
There are two ways to send a SIGKILL signal to the process from the timeout utility. The first way is by specifying the default signal to be sent using the following syntax.
$ timeout -s KILL 1m /path/to/slow-command arg1 arg2
The second way is to first send the
SIGTERM after the initial timeout. Then, wait for another timeout and send a
SIGKILL to the process if it’s still running. This can be done using the following syntax.
$ timeout -k 30 1m /path/to/slow-command arg1 arg2
The process is sent a
SIGTERM signal after 60 seconds. If it is still running, then a
SIGKILL signal is sent after another 30 seconds.
In the event that the
timeout utility is not available, the below 1-liner can be used as an alternative.
$ /path/to/slow-command arg1 arg2 & sleep 60; kill $!
slow-command is started as a background process. The sleep command will then pause till the timeout duration. In our case, it will sleep for 60 seconds. Once 60 seconds has elapsed, the kill command will send a
SIGTERM signal to the
slow-command process. The ‘
$!‘ shell variable will give the PID of the last background job.