Created
February 16, 2010 23:02
-
-
Save gray/306053 to your computer and use it in GitHub Desktop.
run a command with a timeout
This file contains hidden or 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
# 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