Last active
November 22, 2023 23:44
-
-
Save lsferreira42/65d70c8b7588b09b46d3eca50907de2f to your computer and use it in GitHub Desktop.
Timeout implementation using only bash + common linux tools
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function timeout { | |
time_limit=$1 | |
exec_process=$2 # can be a function too | |
# Move the parameters to the 2 position | |
shift 2 | |
# create a pidfile for later reading | |
pid_file=$(mktemp) | |
# This is tricky, it execute the function/process in a subshell, the write the pid to $pid_file | |
($exec_process "$@" & echo $! > $pid_file &) | |
# Retrive the pid to a variable and remove it | |
pid_function=$(cat $pid_file) | |
rm $pid_file | |
# Sleep until timeout time | |
sleep $time_limit | |
# If it's still running after the sleep time, kill it, print a message and then return 1 to indicate a problem | |
if kill -0 $pid_function 2>/dev/null; then | |
echo "The time limit was reached. Killing the process..." | |
kill -9 $pid_function | |
return 1 | |
fi | |
} | |
# Testing, this should exec and ends ok, because the time in sleep is lower than the time for timeout | |
timeout 3 sleep 2 | |
# Testing, this should exec and ends with fail, because the time in sleep is greater than the time for timeout | |
timeout 2 sleep 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment