Shell timeout Command

timeout command used to run command with a time limit. One case is when you know exactly how long you want a process to run for. A common use-case is to have timeout control a logging or data-capture program so that the log files don’t relentlessly devour your hard drive space.

Another case is when you don’t know how long you want a process to run for, but you do know you don’t want it to run indefinitely. You might have a habit of setting processes running, minimizing the terminal window, and forgetting about them. For example:

1
timeout 12 ping 127.0.0.1

By default 12 is second unit, to use a time value measured in minutes, hours or days append an m, h or a d.

Send Right Signal

When timeout wants to stop a program it sends the SIGTERM signal. This politely asks the program to terminate. Some programs may choose to ignore the SIGTERM signal. When that happens, we need to tell timeout to be a little more forceful.

Send KILL signal if program is still running:

1
2
3
# -s: signal
timeout -s SIGKILL 10 tcpdump -i eth0 host 172.18 and tcp 32050
timeout -s SIGKILL 10 tcpdump -w chengdol.pcap &> /dev/null &

We can use the -s (signal) option to tell timeout to send the SIGKILL signal.

Or give it a buffer:

1
2
# -k 20: kill with 20 tolerance
timeout -k 20 10 tcpdump -w chengdol.pcap &> /dev/null &

we use the -k (kill after) option. The -k option requires a time value as a parameter. If tcpdump is still running after 20 seconds, it means the SIGTERM was ignored and timeout should send in SIGKILL to finish the job.

Retrieving the Program’s Exit Code

timeout provides its own exit code, The exit code is 124. This is the value timeout uses to indicate the program was terminated using SIGTERM.

But we may not care about that. We are probably more interested in the exit code from the process that timeout is controlling.

If the execution of the program ends before timeout terminates it, timeout can pass the exit code from the program back to the shell. (no need --preserve-status)

we must use the --preserve-status option if the program timeout but we still want to get its status exit code! For example:

1
timeout --preserve-status 10 <program>
1
2
3
4
5
6
7
8
9
10
# Start Engine Conductor
LogMsg "Starting Engine Conductor Pod..."
(cd $BASE/Engine/engine-conductor; pwd; ./createConductorDepAndSvc.sh $NAME_SPACE $ENGINE_HOST)
check_return_code $?
conductor_pod=$(kubectl get pods -n $NAME_SPACE | grep -i -E $POD_STATES | grep -v NAME|awk '{print $1}'|grep $ENGINE_HOST)
# Check for Engine background processes to complete
# <() is process substitution and redirect the command output to cat
# 其实这里没必要用这种形式 cat <()
timeout --preserve-status 3.0m cat <(check_k8s_start_loop $conductor_pod 7 $NAME_SPACE)
check_timeout_return $? $conductor_pod
0%