Advertisement
devinteske

eval_timeout

Jan 4th, 2013
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.23 KB | None | 0 0
  1. #!/bin/sh
  2. # -*- tab-width:  4 -*- ;; Emacs
  3. # vi: set tabstop=4     :: Vi/ViM
  4. ############################################################ GLOBALS
  5.  
  6. # Global exit status variables
  7. SUCCESS=0
  8. FAILURE=1
  9.  
  10. ############################################################ FUNCTIONS
  11.  
  12. # timeout_watcher $nsecs
  13. #
  14. # No need to call directly. Used by eval_timeout in the following manner:
  15. #     eval_timeout $nsecs $cmd ... | timeout_watcher $nsecs
  16. #
  17. timeout_watcher()
  18. {
  19.     local timeout="$1" tPID tALIVE
  20.  
  21.     read tPID
  22.     while :; do
  23.         kill -INFO $tPID 2> /dev/null || break
  24.         read -t "$timeout" tALIVE
  25.         if [ ! "$tALIVE" ]; then
  26.             # The SIGINFO trap didn't respond in the given timeout...
  27.             # ... assume the sub-shell has hung and kill it.
  28.             kill -9 $tPID
  29.             break
  30.         fi
  31.         sleep $timeout
  32.     done
  33. }
  34.  
  35. # eval_timeout $nsecs $cmd ...
  36. #
  37. eval_timeout()
  38. {
  39.     local timeout="$1"
  40.  
  41.     [ "$timeout" ] || return $FAILURE
  42.     shift
  43.  
  44.     cat <<-EOF | sh -T | timeout_watcher $timeout
  45.         trap 'echo still alive' INFO
  46.         echo \$\$
  47.         eval "$@" 2>&1
  48.     EOF
  49. }
  50.  
  51. ############################################################  MAIN
  52.  
  53. eval_timeout "$@"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement