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 | # -s: signal |
We can use the -s (signal)
option to tell timeout to send the SIGKILL
signal.
Or give it a buffer:
1 | # -k 20: kill with 20 tolerance |
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 | # Start Engine Conductor |