Skip to content

Instantly share code, notes, and snippets.

@lisanna-dettwyler
Last active June 21, 2023 15:42
Show Gist options
  • Save lisanna-dettwyler/78dadfae7642bb473f65eb143db58308 to your computer and use it in GitHub Desktop.
Save lisanna-dettwyler/78dadfae7642bb473f65eb143db58308 to your computer and use it in GitHub Desktop.
Progress-based timeout
#!/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