shell/ target=_blank class=infotextkey>shell脚本功能:
进程监控脚本,每天凌晨自动重启脚本/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 33[60G"
SETCOLOR_SUCCESS="echo -en 33[1;32m"
SETCOLOR_FAILURE="echo -en 33[1;31m"
SETCOLOR_WARNING="echo -en 33[1;33m"
SETCOLOR_NORMAL="echo -en 33[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
为脚本添加执行权限:
chkconfig命令添加自动启动: