专注系统运维、网络架构,研究技术凯发app官方网站的解决方案,记录我的思想轨迹、工作学习、生活和关注的领域
分类: 系统运维
2013-02-07 12:59:13
在上一篇文章 http://blog.chinaunix.net/uid-25266990-id-3477710.html (一个简单的进程监控脚本) 关于每天凌晨自动重启脚本/usr/local/scripts/restart_r.sh,由于该脚本只有重启进程的功能,在使用过程中有很多局限性。
为了能够实现linux中类似网卡启动:server network {start|stop|restart|reload|status}功能,在/etc/init.d/中添加了receve 启动脚本,内容为:
#!/bin/sh # start or stop receve # chkconfig:345 89 17 # description: "receve.php" # source function library if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions elif [ -f /etc/init.d/functions ]; then . /etc/init.d/functions elif [ -f /etc/rc.d/functions ]; then . /etc/rc.d/functions fi #定义启动关闭时,会显示是否ok,并有颜色提示. bootup=color move_to_col="echo -en \\033[60g" setcolor_success="echo -en \\033[1;32m" setcolor_failure="echo -en \\033[1;31m" setcolor_warning="echo -en \\033[1;33m" setcolor_normal="echo -en \\033[0;39m"
#ok 为绿色 function echo_success() { [ "$bootup" = "color" ] && $move_to_col echo -n "[" [ "$bootup" = "color" ] && $setcolor_success echo -n $" ok " [ "$bootup" = "color" ] && $setcolor_normal echo -n "]" echo -ne "\r" echo -e "\n" return 0 } #failed为暗红色 function echo_failure() { [ "$bootup" = "color" ] && $move_to_col echo -n "[" [ "$bootup" = "color" ] && $setcolor_failure echo -n $"failed" [ "$bootup" = "color" ] && $setcolor_normal echo -n "]" echo -ne "\r" echo -e "\n" return 1 } #判断进程的运行状态,并记录pid,我运行着两个进程,所以要记录多次. function isrun { numpro=`/bin/ps -ef | grep "receve.php" | grep -v 'grep'|uniq|wc -l` if [ $numpro -ge 1 ];then export numpro /bin/ps -ef | grep "receve.sh" | grep -v 'grep'|grep -v grep |awk '{print $2}' >/var/run/receve.pid /bin/ps -ef | grep "receve.php" | grep -v 'grep'|grep -v grep |awk '{print $2}' >>/var/run/receve.pid export run=1 else export run=0 fi }
#需要运行的脚本 retval=0 shellbin="/usr/local/scripts/receve.sh" lockfile=/var/lock/subsys/receve # see how we were called. #启动 start() { isrun if [ $run -eq 0 ];then # start receve.php. if [ ! -f $shellbin ];then echo "fatal: no such programme";exit 4; fi echo -n "starting receve: " $shellbin & retval=$? if [ $retval -eq 0 ] ;then touch $lockfile echo_success else echo_failure fi return $retval else echo "receve always on!" fi } #关闭 stop() { isrun if [ $run -eq 1 ];then # stop receve.php. echo -n $"shutting down receve: " for i in `cat /var/run/receve.pid` do kill -9 $i done retval=$? if [ $retval -eq 0 ] ;then rm -f $lockfile echo_success else echo_failure fi return $retval else echo "receve always off!" fi } # call the function we defined case "$1" in start) start ;; stop) stop ;; restart|reload) stop start retval=$? ;; status) status receve retval=$? ;; *) echo $"usage: $0 {start|stop|restart|reload|status}" exit 2 esac exit $retval |
给脚本加执行权限:
# /bin/chmod x /etc/init.d/receve
用chkconfig添加自动启动: