0

I have a simple BASH script that wraps a java program with the intention of restarting it if that application crashes:

STOP=0
while [ "$STOP" -eq 0 ]
do
        echo "Starting"
        exec java com.site.app.Worker
        echo "Crashed"
        sleep 3
done

However if the Java process exits it also quits the bash script so the process is never started again.

E.g. (pointing at a fake class):

$ ./RestartApp.ksh
Starting
Exception in thread "main" java.lang.NoClassDefFoundError: com/site/app/Worker
Caused by: java.lang.ClassNotFoundException: com.site.app.Worker
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.site.app.Worker.  Program will exit.
$

Is there a way I can catch the errors (but still display them) to allow the script to continue running?

1
  • Where is bash file? From where you compiled your class? Commented Mar 18, 2013 at 12:03

2 Answers 2

5

Remove the exec. That's completely replacing the current process (your shell) with the Java VM.

Just remove that and it should work fine.

Sign up to request clarification or add additional context in comments.

Comments

0

As Mat said, what exec does is to replace the current shell process by the Java process. It it fails, there is no-one waiting for it to relaunch it. exec can be a very useful and professional tool to use, but it is rather advanced.

An example of a right use for it would be a script that sets variables or priorities in the current shell, and then exec's the process you are wrapping.

The variable "STOP" does not seem to be used. I would simply go for:

while ! java com.site.app.Worker
do
    echo Failed: Sleeping and restarting >&2
    sleep 3 
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.