From owner-freebsd-questions@FreeBSD.ORG Sun Mar 6 06:39:25 2005 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id 1CB3B16A4CE for ; Sun, 6 Mar 2005 06:39:25 +0000 (GMT) Received: from smtp1.adl2.internode.on.net (smtp1.adl2.internode.on.net [203.16.214.181]) by mx1.FreeBSD.org (Postfix) with ESMTP id 3B0AD43D54 for ; Sun, 6 Mar 2005 06:39:24 +0000 (GMT) (envelope-from malcolm.kay@internode.on.net) Received: from beta.home (ppp38-173.lns1.adl1.internode.on.net [150.101.38.173])j266dLxo044120 for ; Sun, 6 Mar 2005 17:09:22 +1030 (CST) From: Malcolm Kay Organization: at home To: Date: Sun, 6 Mar 2005 17:09:21 +1030 User-Agent: KMail/1.5.4 MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200503061709.21158.malcolm.kay@internode.on.net> Subject: Timeout in bourne scripts. X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sun, 06 Mar 2005 06:39:25 -0000 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