Skip to content

Instantly share code, notes, and snippets.

@gray
Created February 16, 2010 23:02
Show Gist options
  • Save gray/306053 to your computer and use it in GitHub Desktop.
Save gray/306053 to your computer and use it in GitHub Desktop.
run a command with a timeout
# Prefer the timeout program from GNU coreutils.
if command -v timeout > /dev/null 2>&1; then
:
elif command -v gtimeout > /dev/null 2>&1; then
timeout () {
gtimeout $@
}
else
# From "Beginning Portable Shell Scripting", 2008.
timeout () {
timeout=$1
shift
"$@" &
child_pid=$!
(
trap 'kill -TERM $sleep_pid 2>/dev/null ; exit 0' TERM
sleep "$timeout" &
sleep_pid=$!
wait $sleep_pid 2>/dev/null
kill -TERM $child_pid 2>/dev/null
sleep 2
kill -KILL $child_pid 2>/dev/null
) &
alarm_pid=$!
wait $child_pid 2>/dev/null
status=$?
kill -TERM $alarm_pid 2>/dev/null
return $status
}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment