Timeout in bourne scripts.

Malcolm Kay malcolm.kay at internode.on.net
Sat Mar 5 22:39:25 PST 2005


I am running some bourne scripts which occassionally 
lock up with a LAN failure during an 'rdist' transfer 
or other 'ssh' based communication. I need some method
of making these operations timeout in the case of
problems without losing the exit when time out 
doesn't happen.

I have attempted (successfully I think) to roll my own
but I feel sure I must be missing a previous invention
of the wheel.

For what it is worth here is a test of the code I am 
proposing:
----to.sh---------------------------------------------------
#!/bin/sh

timeout()
{  
   debug()
   {
      #comment the next line to disable debug messages
      #echo "$*"
   }
   base=/tmp/`basename $0`.$$

   # use tmax for maximum time (i.e time in seconds to time out)
   # use tres for time resolution (seconds) in testing for completion
   report()
   {  
      $@ &
      echo $! > $base.pid
      wait $! 
      echo $? > $base.stat
   }

   report "$@" &
   sleep $tres
   tmax=$(($tmax-$tres))
   pid=`cat $base.pid`
   debug pid=$pid
   while [ $tmax -gt 0 ]
   do
     ps -p $pid >/dev/null || break
     debug "seconds to time out=$tmax"
     sleep $tres 
     tmax=$(($tmax-$tres))
   done
   [ $tmax -gt 0 ] || kill -KILL $pid > /dev/null 2> /dev/null
   stat=`cat $base.stat`
   rm -f $base.pid $base.stat
   return $stat
}

#test using command line arguments
tmax=$1 tres=$2 timeout "$3"
echo status=$?

#check to see that no unexpected 
#  processes are still running
ps x
-------------------------------------------------------------------------

To test this I use soemthing like:
% ./to.sh 7 1 "sleep 5"
or
% ./to.sh 5 1 "sleep 7"

Any comments appreciated

Malcolm



More information about the freebsd-questions mailing list