Linux下打造Apache和Memcache守护进程
睡梦中,被电话惊醒,web服务器挂了,恼火坏了。登陆服务器一阵忙活,发现apache服务器和memcache服务器非法关闭了。哎,为了睡得安稳,抓紧写个小脚本来监控下appach和memcache吧!很快就有了下面的脚本:然后加入crontab计划任务,如下:
- #!/bin/bash -
- name=`basename $0 .sh`
- function showHelp(){
- echo "Usage: $name"
- echo " $name test|dev"
- exit 1
- }
- if [ $# -ne 0 -a $# -ne 1 ]; then
- showHelp
- fi
- #正式/测试环境
- test=0
- if [ $# -eq 1 ]; then
- # echo "$1"
- if [ "$1" = "dev" -o "$1" = "test" ]; then
- test=1
- else
- showHelp
- fi
- fi
- #echo $test
- websrvkey=/bin/httpd
- websrvbin=/etc/init.d/apachectl
- cachekey=/memcached
- cachebin=/usr/local/memcached/bin/memcached
- cachepid=/usr/local/memcached/memcached.pid
- cachedir=/usr/local/memcached
- #run web server
- function startweb(){
- echo "`date` start websrv..."
- if [ ! -f $websrvbin ]; then
- echo "`date` websrv bin [$websrvbin] not exist..."
- return
- fi
- $websrvbin start
- echo "`date` start websrv complete..."
- }
- #run cache
- function startcache(){
- echo "`date` start cache..."
- if [ $test -eq 1 ]; then
- cachebin=/usr/bin/memcached
- fi
- if [ ! -f $cachebin ]; then
- echo "`date` cache bin [$cachebin] not exist..."
- return
- fi
- if [ ! -d $cachedir ]; then
- echo "`date` cache dir not exist..."
- mkdir $cachedir
- echo "`date` create dir $cachedir"
- fi
- if [ $test -eq 0 ]; then
- $cachebin -d -m 100 -uroot -l 0.0.0.0 -p 11000 -c 512 -P $cachepid
- else
- $cachebin -d -m 128 -l 192.168.119.60 -p 12000 -u ossh
- fi
- echo "`date` start cache complete..."
- }
- cnt=`ps -ef | grep $websrvkey | grep -vc grep`
- # echo $cnt
- if [ $cnt -le 0 ]; then
- startweb
- fi
- cnt=`ps -ef | grep /memcached | grep -vc grep`
- #echo $cnt
- if [ $cnt -le 0 ]; then
- startcache
- fi
把上面的脚本保存为monitorWebSrv.sh,并对该文件赋予可执行权限,进行如下操作:
- chmod +x /etc/app/slightphp/public/csevent/bin/crontab/monitorWebSrv.sh
- * * * * * /etc/app/slightphp/public/csevent/bin/crontab/monitorWebSrv.sh >> /tmp/monitorWebSrv.log
- * * * * * sleep 30; /etc/app/slightphp/public/csevent/bin/crontab/monitorWebSrv.sh >> /tmp/monitorWebSrv.log
为什么加两条呢?为了每隔30秒执行一次!
对于shell和crontab,请参阅以前的blog:shell脚本比较运算符及逻辑运算符小结 、Linux Shell脚本逻辑操作符简介 及Linux crontab命令小结。