Archive for August, 2013

Init script for java jar

Tuesday, August 20th, 2013

Heres an example for starting a jar process with a single init script


#!/bin/sh
#
# init script for a Java application
#
# chkconfig: - 85 15
pid=0

# Check the application status
#
# This function checks if the application is running
check_status() {

s=`ps -e -o pid,cmd --sort cmd | grep "java -jar start.jar" | grep -v "grep " | tail -n1 | awk '{ print $1 }'`

# If somethig was returned by the ps command, this function sets the PID
if [ $s ] ; then
pid=$s
fi

# In any another case, set pid to 0
pid=0

}

# Starts the application
start() {

# At first checks if the application is already started calling the check_status
# function
check_status

if [ $pid -ne 0 ] ; then
echo "The application is already started"
exit 1
fi

# If the application isn't running, starts it
echo -n "Starting application: "

# Redirects default and error output to a log file
cd /home/www/dinhvan.vicosys.com.hk/htdocs/extension/ezfind/java
java -jar start.jar >> /var/log/ezfind.log 2>&1 &
echo "OK"
}

# Stops the application
stop() {

# Like as the start function, checks the application status
check_status

if [ $pid -eq 0 ] ; then
echo "Application is already stopped"
exit 1
fi

# Kills the application process
echo -n "Stopping application: "
kill -9 $pid &
echo "OK"
}

# Show the application status
status() {

# The check_status function, again...
check_status

# If the PID was returned means the application is running
if [ $pid -ne 0 ] ; then
echo "Application is started"
else
echo "Application is stopped"
fi

}

# Main logic, a simple case to call functions
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart|reload)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac

exit 0