Friday, January 27, 2012

CentOS PHP FastCGI init script

#!/bin/sh  
#
# php-fcgi      Startup script for PHP FCGI
#  
# chkconfig:   345 86 14   
# description:  PHP FCGI server   
# pidfile:     /var/run/php-fcgi/pid  
  
PATH=/sbin:/bin:/usr/bin:/usr/sbin
  
# Source function library.  
. /etc/rc.d/init.d/functions
  
# Get config.   
test -f /etc/sysconfig/network && . /etc/sysconfig/network
  
# Check that we are root ... so non-root users stop here  
[ `id -u` = 0 ] || exit 1
  
# Check that networking is up.  
[ "${NETWORKING}" = "yes" ] || exit 0
 
USER=apache
RUNDIR_OWNER=root:apache

PHP_FCGI_CHILDREN=15
PHP_FCGI_MAX_REQUESTS=1000
ALLOWED_ENV="PATH USER"
  
RUNDIR="/var/run/php-fcgi"
BIND="$RUNDIR/socket"
PIDFILE="$RUNDIR/pid"SUBSYS_FILE=/var/lock/subsys/php-fcgi
PHP_CGI=/usr/bin/php-cgi

ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS FCGI_WEB_SERVER_ADDRS"

RETVAL=0

start() {
        if [ ! -d "$RUNDIR" ] ; then
            if [ ! -e "$RUNDIR" -a ! -h "$RUNDIR" ]
            then
                mkdir -p "$RUNDIR" || exit 1
            fi
        fi
        chown -R $RUNDIR_OWNER "$RUNDIR"
        chmod 0775 "$RUNDIR"

        # clean environment
        E=
        for i in $ALLOWED_ENV; do E="$E $i=${!i}"; done


        echo -n "Starting PHP FastCGI: "
        daemon --user $USER --pidfile $PIDFILE "env - $E $PHP_CGI -q -b $BIND&> /dev/null &"
        RETVAL=$?
        pid=`pidof php-cgi`
        if [ -n "$pid" ]; then
            echo $pid > $PIDFILE
        fi
        echo  
        touch $SUBSYS_FILE
        return $RETVAL
}

stop(){
        echo -n "Stopping PHP FastCGI: "
        killproc -p $PIDFILE php-fcgi
        RETVAL=$?
        echo  
        rm -f $SUBSYS_FILE
        return $RETVAL
}

restart(){
        stop
        start
}

condrestart(){
    [ -e $SUBSYS_FILE ] && restart
    return 0
}


# See how we were called.  
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status -p $PIDFILE php-fcgi
        ;;
    restart)
        restart
        ;;
    condrestart)
        condrestart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart}"  
        RETVAL=1
esac

exit $RETVAL