Linux下的常駐進程的作用不可忽略,但這裡面的問題也不能忽略,怎麼啟動進程,怎麼結束進程,怎麼在進程掛掉之後重啟進程都要設計的合理。下面看一個shell控制的php常駐進程的例子。
不廢話,直接撈干貨,上代碼,通過代碼來講解更容易理解:
#!/bin/sh
#filename test.sh
#絕對定位該文件的位置,不隨執行目錄而變化
cd $(cd "$(dirname "$0")";pwd)
readonly path=$(pwd)/
file=$1;
RunFile="${path}data/${file}.run"
DieFile="${path}data/${file}.die"
readonly file="${path}${file}.php"
if [ ! -f "$file" ]; then
echo "please select a exists file"
elif [ ! -f "$RunFile" ]; then
#這裡進行判斷如果RunFile文件不存在,則表示該進程不存在,下面啟動進程 echo $$>${RunFile}
while true
do
if [ ! -f $DieFile ]; then
#這裡如果DieFile文件不存在,則表示程序繼續執行,否則進入else,執行退出操作
/usr/bin/php -f ${file}
touch $RunFile
sleep 1
else
#如果DieFile文件存在清除RunFile和DieFile退出
if rm -rf $RunFile && rm -rf $DieFile ; then
exit
fi
fi
done
else
#這裡是在存在RunFile的情況下試圖啟動該進程
oldpid=`cat $RunFile`
newpid=`ps aux | grep "process.sh $1" | grep -v grep | grep "$oldpid" | awk '{print $2}'`
if [[ $oldpid -eq $newpid ]]; then
#如果RunFile中的進程號和正在運行的目標進程號一致,表明一切安好^_^
echo "the process is runing now"
exit
else
#如果用RunFile中的進程號匹配不到正在運行的目標進程,則表示進程有問題,直接刪除RunFile並結束運行的進程
echo "error situation,kill the run process and delete the run file"
ps aux | grep "process.sh $1" | grep -v 'grep' | awk '{print $2}' | grep -v $$ | xargs --no-run-if-empty kill
if [ $? -eq 0 ]; then
rm -f $RunFile
else
echo $?>${path}/data/error
fi
fi
fi
只裡面有幾個要強調的地方:
自動重啟可以放在crontab中,每隔一段時間執行一次,具體情況具體對待。
crontab -e
#打開當前用戶日程表,添加模式
#日程表中有5個星號,f1,f2,f3,f4,f5,
#其中f1表示分,f2表示時,f3表示日,f4表示月,f5表示一個星期第幾天
#*表示每分/時/日/月/周天,*/n表示每n分/時/......執行一次
*/2 * * * * /root/test.sh
#沒2分鐘執行一次
這樣一個完整的常駐進程功能就完成了,想要終止進程是只需要在對應的目錄下進行touch ${DieFile}即可。