Introduction
Configuring a java application as a Linux service, makes management of application easier.
Steps
1. Create following init.d script under /etc/init.d directory. Suppose its name is service_name.sh.
#!/bin/bash
#
# source function library
. /etc/init.d/functions
RETVAL=0
EXECUTABLE="path_to_java_executable"
WORKDIR="service_working_directory"
LAUNCH_OPTIONS="application_launch_parameters"
GREP_EXPR="%application_name%"
PIDFILE="%application_name%.pid"
start() {
echo -n $"Starting %application_name% service: "
cd $WORKDIR
if [[ -f $PIDFILE ]];then
echo "pidfile is already existing. Cancelling service start."
return
fi
nohup ${EXECUTABLE} ${LAUNCH_OPTIONS} &
RETVAL=$?
pid=$(ps -ef | grep ${GREP_EXPR} | grep -v grep| grep -v service | grep -v init.d | awk '{print $2}')
echo $pid > $PIDFILE
ps -fp $pid
if [ $RETVAL -eq 0 ]; then
echo "%application_name% service started successfully at pid $pid"
else
echo "%application_name% service start failed."
fi
}
stop() {
echo -n $"Shutting down %application_name% service: "
cd $WORKDIR
kill `cat $PIDFILE`
rm -f $PIDFILE
RETVAL=$?
}
status() {
status="NOT Running"
if [[ ! -z `ps -ef | grep ${GREP_EXPR} | grep -v grep` ]];then
status="Running"
fi
echo "Service is $status"
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
stop
start
;;
status)
status
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit $RETVAL
2. Use following commands to manage service.
Bash> service service_name start
Bash> service service_name status
Bash> service service_name stop
A pid file containing pid of the process launched will be created in service working directory. When service is stopped pid file will be removed.
Summary
Feel free to share your comments to http://el-harezmi.blogspot.com on design and any typos, incorrect or inaccurate expressions you see.
Comments
Post a Comment