2017-02-19 67 views
0

我有一個簡單的腳本來檢查Web服務器是否正在運行,如果沒有,嘗試啓動它。我把這個腳本放在rc1.d中,這樣我的web服務器就不會停止運行。 現在,如果我想停止重新啓動webserver,我必須殺死這個腳本。 現在的問題是:如何更改父級腳本,以便手動阻止Web服務器短時間重新啓動? 請不要發佈與特定發行版相關的答案。 這裏是我的腳本:臨時停止守護進程的持久進程而不會將其殺死

#!/bin/sh 

if [ "$1" = "stop" ] ; then 
    echo "Stoping lighttpd..." 
    killall lighttpd 
    PID=`pidof lighttpd` 
    if [ "$PID" != "" ] ; then 
     kill -9 $PID 
    fi 
    exit; 
fi 

PID=`pidof lighttpd` 
if [ "$PID" == "" ] ; then 
    echo "Starting lighttpd..." 
    nohup lighttpd >/dev/null 2>/dev/null & 
fi 

PID=`pidof lighttpd` 

while [ "1" == "1" ] 
do 
    PID=`pidof lighttpd` 
    sleep 3 
    if [ "$PID" == "" ] ; then 
     echo "Restarting lighttpd..." 
     nohup lighttpd >/dev/null 2>/dev/null & 
     sleep 2 
    fi 
done 

有沒有什麼辦法,我可以改變它,所以沒有殺死這個劇本我就可以停止lighttpd的?

+2

發送的監控進程'SIGSTOP',做你想做的事,然後把它'SIGCONT'到可能繼續嗎? –

回答

1

用於此目的的解決方案之一是有一個臨時文件充當標誌,指示您的腳本不採取措施。

你的監控腳本應該是這樣的:

#!/bin/bash 

if [ "$1" = "stop" ] ; then 
    echo "Stoping lighttpd..." 
    killall lighttpd 
    PID=$(pidof lighttpd) 
    if [ "$PID" != "" ] ; then 
     kill -9 $PID 
    fi 
    exit; 
fi 

MSG="Starting lighttpd..." 
while [ true ]; do 
    PID=$(pidof lighttpd) 
    if [ -z "$PID" -a ! -f /var/run/.pause_monitor_lighttpd ] ; then 
     echo "$MSG" 
     nohup lighttpd >/dev/null 2>/dev/null & 
    fi 
    MSG="Restarting lighttpd..." 
    sleep 3 
done 

然後,暫停監控,你會:

touch /var/run/.pause_monitor_lighttpd 

,並取消暫停監測:

rm -f /var/run/.pause_monitor_lighttpd 

正如馬克評論以上,另一種解決方案是使用SIGSTOPSIGCONT信號暫時停止您的腳本。請記住,如果您的腳本被其他機制重新啓動,它會立即啓動並重新啓動Web服務器。假設你的腳本被稱爲monitor_lighttpd.sh,你會使用這個暫停監控:

pkill -STOP -f '/bin/bash .*/monitor_lighttpd.sh' 

,然後,以取消暫停:

pkill -CONT -f '/bin/bash .*/monitor_lighttpd.sh' 

一般提示:

  • 使用$(command)代替`command`
  • 在檢測到病症(PID=...)之後並未採取行動它(if [ $PID...),如果可能,這將有更大的機會改變你的條件
  • ,使用守護進程的初始化腳本,而不是手動啓動/停止它。 /etc/init.d/lighttpd stop代替killall lighttpd(確切的使用取決於你的系統)