Java – Start java process at boot and auto-restart on death

bashinit.djavalinux

I have two requirements for my Java app. If it dies, restart it. If the server reboots, restart it – simple enough. Using the answer here I have a script that will restart when the java application dies.

#!/bin/bash

until java -Xms256m -Xmx768m -jar MyApp.jar; do
    echo "MyApp crashed with exit code $?.  Respawning... " >&2
    sleep 5
done

I can run this with "nohup restart_script.sh &" and it will run all day long without issue. Now for the startup requirement. I took the /etc/init.d/crond script and replaced the crond binary with my script but it hangs on startup.

#!/bin/bash
#
# Init file for my application.
#
. /etc/init.d/functions

MYAPP=restart_script.sh
PID_FILE=/var/run/myapp.pid

start(){
        echo -n "Starting My App"
        daemon --user appuser $MYAPP
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/myapp
        return $RETVAL
}

stop(){
        echo -n "Stopping my application"
        killproc $MYAPP
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/myapp
        return $RETVAL
}

...

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
...
esac

When I run /sbin/service myapp start the script starts but hangs the console. I have tried "daemon –user appuser nohup $MYAPP &" and I am immediately returned to the prompt without any [OK] indication and when I do a ps, I still see that the init is hung. Any ideas how to call a script within the init script and get it to return properly?

Thanks,

Greg

Best Answer

The daemon function on my machine (old RedHat) does not return until the executed program returns. So you are going to need to have your little utility script do the forking.

Try writing your utility like this:

#!/bin/bash

(
    until java -Xms256m -Xmx768m -jar MyApp.jar; do
        echo "MyApp crashed with exit code $?.  Respawning... " >&2
        sleep 5
    done
) &

How this works. Putting a command in parentheses starts code running in a new process. You put the process in the background so the original process will return without waiting for it.