shell scripting, how to auto-timeout?

Maxim Khitrov mkhitrov at gmail.com
Thu Jan 22 16:35:02 PST 2009


On Thu, Jan 22, 2009 at 5:58 PM, Nerius Landys <nlandys at gmail.com> wrote:
> Actually, because of the "exec" in the parent script, the line below
> it, the "killing terminator process" line, never gets reached.  So the
> terminator process that waits to kill its parent always waits the full
> 5 seconds in the background.  If I pipe the output of the parent
> script through less, it waits 5 seconds before it reaches the end of
> the output.  That is annoying.  Is there any way to solve that?
>

I see what you mean. Here's another option without exec:

#!/bin/sh -T

kill_all()
{
	echo 'killing everything'
	kill $SPID $CPID 2> /dev/null
	exit 0
}

trap kill_all SIGCHLD

./child &
CPID=$!

sleep 5 &
SPID=$!

echo "child is $CPID"
echo "sleeper is $SPID"
wait

Here I'm using the fact that the termination of any child process
causes SIGCHILD to be sent to the parent. Notice the '-T' in the first
line; this is important, because without it the 'wait' call isn't
interrupted until both children are dead. Unfortunately, this is a
non-standard option, so you'll have to check if it is supported in
your environment.

- Max


More information about the freebsd-questions mailing list