Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!ucsd!pacbell.com!pacbell!sactoh0!jak From: jak@sactoh0.UUCP (Jay A. Konigsberg) Newsgroups: comp.unix.questions Subject: Re: Timeout on shell command. Message-ID: <3716@sactoh0.UUCP> Date: 16 Aug 90 02:12:09 GMT References: <1990Aug12.221658.27776@uncle.uucp> Reply-To: jak@sactoh0.UUCP (Jay A. Konigsberg) Organization: SAC-UNIX, Sacramento, Ca. Lines: 48 In article <1990Aug12.221658.27776@uncle.uucp> donlash@uncle.UUCP (Donald Lashomb) writes: >In article brister@decwrl.dec.com (James Brister) writes: >>I'd like to have a shell script run a command, but if that command doesn't >>finish in X seconds, then the script should kill it, if the command >>finishes sooner then the script should immediately continue. Any ideas on ============================================================= >>how one could achieve this? > >I'd approach it like this- > >#!/bin/sh ># ># run the command in the background ># remember its process ID ># sleep for X seconds ># kill the background command --- note: if ># the background command is finished, then ># the kill will fail benignly. ># >command & >cmdpid=$! >sleep $X >kill $cmdpid > When I saw the original post, I almost answered with this type of solution. However, it lacks an important part of the request. If the command finishes early, execution will still wait for the sleep to complete. However, there just may be a way if the sleep is placed in its own file. # main program file SEC={number here} # set the number of seconds to wait command & # execute in background cmdpid = $! # save the PID sleepit $SEC $cmdpid & # sleep in background wait $cmdpid # wait for the process to complete or be killed # sleepit - sleep $1 sec and then kill -9 $2 sleep $1 kill -9 $2 2>/dev/null #don't want those nasty error messages. My thanks to Donald Lashomb's post. Without it, I wouldn't have come up with this solution. -- ------------------------------------------------------------- Jay @ SAC-UNIX, Sacramento, Ca. UUCP=...pacbell!sactoh0!jak If something is worth doing, its worth doing correctly.