Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

自製 PHP-FPM 啟動/關閉/重啟管理腳本(含開機自啟)

思路

1. 用 function 模組搭配 case 多分支判斷;2. 透過 # chkconfig: 2345 43 89 註解實現開機自啟(前提是腳本放在 /etc/init.d/、給予可執行權限,再 chkconfig --add phpd);3. 每次指令是否成功,用 $? 是否為 0 來回饋。

腳本內容

#!/bin/bash
# php-fpm Start/Stop php-fpm
#
# chkconfig: 2345 43 89
#author andy
#date 20161218
#function php-fpm manager
#version 1.0

. /etc/init.d/functions

# 以連接埠/程序名判斷服務狀態
check=`netstat -lnutp|grep php-fpm|wc -l`

function usage(){
    echo "usage:$0 {start|stop|restart|status}"
    exit
}

function start(){
    if [ "$1" = "start" -a $check -ne 0 ];then
        action "php is already started!" /bin/false
        exit
    elif [ "$1" = "start" -a $check -eq 0 ];then
        sleep 1
        /usr/local/sbin/php-fpm
        if [ $? = 0 ];then
            action "php start successfully!" /bin/true
        else
            action "php start failed!" /bin/false
            exit
        fi
    fi
}

function stop(){
    if [ "$1" = "stop" -a $check -eq 0 ];then
        action "php is not running!" /bin/false
        exit
    elif [ "$1" = "stop" -a $check -ne 0 ];then
        killall php-fpm
        sleep 1
        if [ $? = 0 ];then
            action "php stoped successfully!" /bin/true
        else
            action "php stoped failed!" /bin/false
            exit
        fi
    fi
}

function restart(){
    if [ "$1" = "restart" -a $check -eq 0 ];then
        action "php is not running!" /bin/false
        sleep 1
        /usr/local/sbin/php-fpm
        if [ $? = 0 ];then
            action "php start successfully!" /bin/true
        else
            action "php start failed!" /bin/false
            exit
        fi
    elif [ "$1" = "restart" -a $check -ne 0 ];then
        killall php-fpm
        if [ $? = 0 ];then
            action "php stoped successfully!" /bin/true
        else
            action "php stoped failed!" /bin/false
        fi
        sleep 1
        /usr/local/sbin/php-fpm
        if [ $? = 0 ];then
            action "php start successfully!" /bin/true
        else
            action "php start failed!" /bin/false
            exit
        fi
    fi
}

function status(){
    if [ "$1" = "status" -a $check -eq 0 ];then
        echo "php is not running!"
        exit
    elif [ "$1" = "status" -a $check -ne 0 ];then
        echo "php is running"
        exit
    fi
}

case "$1" in
    start)   start $1 ;;
    stop)    stop $1 ;;
    restart) restart $1 ;;
    status)  status $1 ;;
    *)       usage $1 ;;
esac

幾處可以更好的地方

用 pidfile 取代 killall:killall php-fpm 會把同機上所有 php-fpm master 一起殺掉。若你跑多個 pool,請改用 cat /usr/local/var/run/php-fpm.pid | xargs kill,只動自己這一份。

用 ss 精確判斷:grep php-fpm 是子字串比對,容易誤判;ss -lntp | grep -q php-fpm 更準。

補上 usage 的預設分支呼叫:目前 *) usage $1 已處理,但 $1 為空時仍會落到 usage,行為正確;若日後擴充參數,記得同步更新。

rc 不回傳:case 的最後一個指令成敗會成為腳本退出碼,若需要嚴格回饋,建議每個分支結尾明確 exit 0 或 exit 1。

本文整理自 TechArticle 技術文章。

Copyright © Linux教程網 All Rights Reserved