Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 22 Jan 2009 16:33:28 -0500
From:      Maxim Khitrov <mkhitrov@gmail.com>
To:        Nerius Landys <nlandys@gmail.com>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: shell scripting, how to auto-timeout?
Message-ID:  <26ddd1750901221333x5356f4f3l6b6410fc05d4e6d4@mail.gmail.com>
In-Reply-To: <560f92640901221241y4fc1620aree083a812c1f3c8d@mail.gmail.com>
References:  <560f92640901221241y4fc1620aree083a812c1f3c8d@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, Jan 22, 2009 at 3:41 PM, Nerius Landys <nlandys@gmail.com> wrote:
> This is a shell scripting question, it is not specific to FreeBSD.
>
> I am writing a script that I want to terminate after 1 second (because
> it has the potential to infinite loop).  The script I have so far is:
>
> #!/bin/sh
> cd `dirname "$0"`
> CLASSPATH=mapgen.jar
> export CLASSPATH
> /usr/local/bin/java PipeGenerator $*
>
> The java process has the potential to run forever, and I want it to
> run for at most 1 second then get killed.  I could write a parent
> script that somehow gets the PID of the child script, but the problem
> is that the java program writes to standard out, the result of the
> program is written to standard out.  I also don't really want to share
> a PID with a temporary file.
>
> So what I might do is this:
>
> /usr/local/bin/java PipeGenerator $* &
> sleep 1
> <kill the java command if not already killed>
>
> Also with the above code I would be waiting for 1 second even if the
> java process finished sooner.  But that is a penalty I'm willing to
> pay, unless there is a more elegant solution.
>
> How do I do this?

Give this a try:

#!/bin/sh

java()
{
	echo 'start'
	sleep 5
	echo 'stop'
}

sleep 1 && kill $$ &
java
kill $!

Replace the java function with your code. The basic idea is that you
start a child process which will kill its parent after 1 second
(parent pid is $$, child is $!). If the java command terminates before
then, the child is killed. Test both cases out by commenting out
'sleep 5' line above.

- Max



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?26ddd1750901221333x5356f4f3l6b6410fc05d4e6d4>