Daemonize a script
Sometimes it is required to start script as daemon (for example Django site in development mode), and I want to provide guidance how to do it in Fedora 9.
First, it is required to write auxiliary bash-script for running necessary script (let's call it 'site.sh'):
#!/bin/sh
cd /path/to/site/
nohup python manage.py runserver 0.0.0.0:8080 --noreload > site.log &
echo "${!}" > /var/run/site.pid
In this script I changed directory to site location, and ran it via 'nohup' command. Also I took PID of created process via '${!}' to manage it later.
This script should be run under root privileges and should be checked via 'ps aux | grep python' for equality of PID of running process and stored in /var/run/site.pid.
If everything is fine, let's move forward and create init-script (let's call it 'site'):
#! /bin/sh
# Startup script for site
#
# chkconfig: 2 96 04
# description: site service
# Source function library.
. /etc/rc.d/init.d/functions
prog="site"
DAEMON=/path/to/site.sh
pidfile=/var/run/site.pid
[ -f $DAEMON ] || exit 0
start() {
echo -n $"Starting $prog: "
daemon $DAEMON
RETVAL=$?
echo
return $RETVAL
}
stop() {
if test "x`cat $pidfile`" != x; then
echo -n $"Stopping $prog: "
killproc $prog
echo
fi
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
rm -f $pidfile
fi
return $RETVAL
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status corpsite
;;
restart)
stop
start
;;
condrestart)
if test "x`cat $pifile`" != x; then
stop
start
fi
;;
*)
echo "Usage: $0 {start|stop|restart|condrestart|status}"
exit 1
;;
esac
exit $RETVAL
This script should be stored in /etc/init.d. Now try to run it using '/sbin/service site start' and try other commands. Please notice these few issues:
- 'prog' variable is used for information messages and for killing the process. Killing will be worked via PID (because we can't use script name - it will be 'python' and probably you could have other running python scripts) and PID will be gotten from /var/run/$prog.pid. So the name of pidfile and 'prog' should be the same.
- 'DAEMON' variable is a path for script above. It should be changed to accommodate the location of the script.
So, the last step is automatically loading/unloading script during startup/shutdown the OS. This is pretty easy - I have already prepared all information for 'chkconfig' in the init-script (see corresponded remarks in a header). Only enter command '/sbin/chkconfig --add site' and that's all - the script will be loaded/unloaded automatically after next startup.
DOWNLOAD - daemon.tar.gz (1.03KB)
Comments
Post a Comment