Running arbitrary program as daemon from init script
The command "doesn't complete" because the daemon
function does not run your application in the background for you. You will need to add an &
to the end of your daemon
command like so:
daemon --user someproguser $exec &
If someprog
doesn't handle SIGHUP
, you should run the command with nohup
to ensure that your process won't receive SIGHUP
which tells your process to exit when the parent shell exits. That would look like this:
daemon --user someproguser "nohup $exec" &
In your stop
function, killproc "exec"
isn't doing anything to stop your program. It should read like so:
killproc $exec
killproc
requires the full path to your application to stop it properly. I've had some trouble with killproc
in the past, so you can also just kill the PID in the PIDFILE you should be writing someprog
's PID to with something like this:
cat $pidfile | xargs kill
You can write the PIDFILE like this:
ps aux | grep $exec | grep -v grep | tr -s " " | cut -d " " -f2 > $pidfile
where $pidfile
points to /var/run/someprog.pid
.
If you want [OK] or [FAILED] on your stop
function, you should use the success
and failure
functions from /etc/rc.d/init.d/functions
. You don't need these in the start
function because daemon
calls the appropriate one for you.
You also only need quotes around strings with spaces. It's a style choice, though, so it's up to you.
All these changes look like this:
#!/bin/bash
#
# /etc/rc.d/init.d/someprog
#
# Starts the someprog daemon
#
# chkconfig: 345 80 20
# description: the someprog daemon
# processname: someprog
# config: /etc/someprog.conf
# Source function library.
. /etc/rc.d/init.d/functions
prog=someprog
exec=/usr/local/bin/$prog
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
lockfile=/var/lock/subsys/$prog
pidfile=/var/run/$prog
RETVAL=0
check() {
[ `id -u` = 0 ] || exit 4
test -x $exec || exit 5
}
start() {
check
if [ ! -f $lockfile ]; then
echo -n $"Starting $prog: "
daemon --user someproguser "nohup $exec" &
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
touch $lockfile
ps aux | grep $exec | grep -v grep | tr -s " " | cut -d " " -f2 > $pidfile
fi
echo
fi
return $RETVAL
}
stop() {
check
echo -n $"Stopping $prog: "
killproc $exec && cat $pidfile | kill
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
rm -f $lockfile
rm -f $pidfile
success; echo
else
failure; echo
fi
echo
return $RETVAL
}
restart() {
stop
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
RETVAL=2
esac
exit $RETVAL