A typical init script provides start, stop, restart, and status service to daemon program.
The
start service will run the daemon program and create a lock file in /var/lock/subsys. This lock file will
be use by status service.
To avoid mulitple instance of the deamon program, create a pid file so that the daemon function can check the process id. The deamon function will execute the daemon program if there is no pid file or there is pid file but has invalid process id. Its up to daemon program or init script to create the pid file.
start() {
echo -n $"Starting $PROG_NAME: "
# start daemon
daemon $DAEMON
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $PROG_LOCK_FILE
return $RETVAL
}
The
stop service will kill the daemon program, delete the lock file and pid file. killproc function will delete the pid file.
stop() {
# stop daemon
echo -n $"Stopping $PROG_NAME: "
killproc $DAEMON
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f $PROG_LOCK_FILE
return $RETVAL
}
The
restart service basically calls stop and start services.
restart)
stop
start
;;
The
status service will tell if the daemon is running or stopped. This depends on the lock file and process id of the daemon program. The process id is checked using pid file and using the pidof.
status)
status $DAEMON
RETVAL=$?
;;
About pidof:
- if the daemon program is a script that is using env to call the interpreter (e.g. #!/bin/env ruby, #!/bin/env python), the pidof will fail to return process id of the script.
To setup the daemon program to run as user account:
- specify the user name in daemon, status and killproc functions
- if the pid file is created by the daemon program, specify the location of pid file
Complete init script:
#!/bin/sh
#
# "$Id: mydaemon,v 1.10 2012/06/19 10:10:10 $"
#
# Startup/shutdown script for the mydaemon.
#
# Linux chkconfig stuff:
#
# chkconfig: 2345 99 00
# description: Startup/shutdown script for the mydaemon.
. /etc/rc.d/init.d/functions
export DISPLAY=:0
DAEMON=/path/to/mydaemond
PROG_NAME=mydaemon
PROG_LOCK_FILE=/var/lock/subsys/mydaemond
RETVAL=0
start() {
echo -n $"Starting $PROG_NAME: "
# start daemon
daemon $DAEMON
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $PROG_LOCK_FILE
return $RETVAL
}
stop() {
# stop daemon
echo -n $"Stopping $PROG_NAME: "
killproc $DAEMON
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f $PROG_LOCK_FILE
return $RETVAL
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status $DAEMON
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
exit 2
esac
exit $RETVAL