--- Simon Geard <[EMAIL PROTECTED]> wrote:
> On Mon, 2005-09-12 at 12:00 -0700, Brandin Creech wrote:
> > Here is a generic method to implement a timeout in BASH.
>
> Looks good - I use something similar at work to scp a file to a bunch of
> other machines from a cron job.
> pid=$! #pid of last backgrounded process
> sleep 20
> if ps -p $pid | grep scp; then # make sure pid isn't reused.
> kill $pid
> fi
Yeah, in my previous code I made the assumption that $pid will not be reused
by something else that is legitimate, so if you're using randomly-assigned
PIDs, there is no way to guarantee that $pid will not be reused. Checking for
"ps -p $pid | grep scp" is a way to verify that you're killing the right
thing, as you've done. But I get nervous about using ps <something> | grep in
scripts; here's a way to remove the assumption I made from my outline:
------------------------------------------------------------------------
#!/bin/bash
ME=$(basename "$0")
timeout=10
script_pid=$$
(
sleep $timeout
if kill $script_pid &>/dev/null
then
echo "Time limit of $timeout seconds exceeded; terminating $ME."
fi
) &
sleep_pid=$!
# This block represents the set of commands that may take a long time.
# It simulates a coin-toss, and if it lands on heads (0), completes in 1
# second. If it lands on tails (1), it waits a long time.
if [ $((RANDOM % 2)) = "0" ]
then
sleep 1
else
sleep 1000000
fi
# At this point, script has succeeded without hanging, so get rid of the
# auto-kill process (sleep_pid):
kill $sleep_pid
------------------------------------------------------------------------
> Incidentally, does anyone know a better way of making ssh/scp timeout if
> it's sitting waiting for the user to enter a password?
I haven't tried it, but scp(1) and ssh(1) both say this on my system:
-o ssh_option
Can be used to pass options to ssh in the format used in
ssh_config(5). ...
...
ConnectionAttempts
ConnectTimeout
ControlMaster
...
Have you tried the ConnectTimeout option? It may be what you need. However,
maybe not; I checked ssh_config(5) for details and it says that the timeout
value is only used if the host is unreachable.
______________________________________________________
Yahoo! for Good
Donate to the Hurricane Katrina relief effort.
http://store.yahoo.com/redcross-donate3/
--
http://linuxfromscratch.org/mailman/listinfo/blfs-support
FAQ: http://www.linuxfromscratch.org/blfs/faq.html
Unsubscribe: See the above information page