Last active
June 21, 2023 15:42
-
-
Save lisanna-dettwyler/78dadfae7642bb473f65eb143db58308 to your computer and use it in GitHub Desktop.
Progress-based timeout
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
#!/usr/bin/env bash | |
# This is an alternative for the GNU coreutils timeout, which resets the timer | |
# when the program writes to stdout. This allows setting much smaller timeout | |
# values for programs that regularly print progress messages, which allows | |
# progress stalls to be detected more quickly, saving execution time in testing | |
# contexts. | |
set -e | |
tmp=$(mktemp -d) | |
trap 'rm -rf -- "$tmp"' EXIT | |
fifo=$tmp/fifo | |
mkfifo $fifo | |
timeout=$1 | |
shift | |
last_updated=$(date +%s) | |
"${@}" > $fifo & | |
pid=$! | |
while IFS= read -t $timeout -r line; do | |
echo "$line" | |
last_updated=$(date +%s) | |
done < $fifo | |
if [ $(( $(date +%s) - $last_updated )) -ge $timeout ]; then | |
echo "Timeout: no activity for $timeout seconds" | |
kill $pid | |
wait -n | |
exit 124 | |
fi | |
wait ${pid} | |
exit $! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment