OT: How to set a timeout for a process
Devin Teske
dteske at vicor.com
Thu Jan 27 17:38:44 UTC 2011
On Thu, 2011-01-27 at 03:37 -0500, Aryeh Friedman wrote:
> I have a script that may or not hang (the reasons why it hangs are
> unimportant here) and need to call it from an other script and need to
> say if it hangs to give up after X seconds and just continue the
> script (no harm done if it fails)
#!/bin/sh
# -*- tab-width: 4 -*- ;; Emacs
# vi: set tabstop=4 :: Vi/ViM
############################################################ GLOBALS
# Global exit status variables
SUCCESS=0
FAILURE=1
############################################################ FUNCTIONS
# timeout_watcher $nsecs
#
# No need to call directly. Used by eval_timeout in the following
manner:
# eval_timeout $nsecs $cmd ... | timeout_watcher $nsecs
#
timeout_watcher()
{
local timeout="$1" tPID tALIVE
read tPID
while :; do
kill -INFO $tPID 2> /dev/null || break
read -t "$timeout" tALIVE
if [ ! "$tALIVE" ]; then
# The SIGINFO trap didn't respond in the given timeout...
# ... assume the sub-shell has hung and kill it.
kill -9 $tPID
break
fi
sleep $timeout
done
}
# eval_timeout $nsecs $cmd ...
#
eval_timeout()
{
local timeout="$1"
[ "$timeout" ] || return $FAILURE
shift
cat <<-EOF | sh -T | timeout_watcher $timeout
trap 'echo still alive' INFO
echo \$\$
eval "$@" 2>&1
EOF
}
############################################################ MAIN
eval_timeout "$@"
> _______________________________________________
> freebsd-questions at freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "freebsd-questions-unsubscribe at freebsd.org"
More information about the freebsd-questions
mailing list