用 vim建立 /etc/init.d/keepalive文件

#!/bin/bash
# chkconfig: 2345 10 90
# description: Start and Stop KEEP_ALIVE PHP="/usr/local/php/bin/php" KEEP_ALIVE_DIV="/home/wwwroot/keep-alive.qunarmei.com"
KEEP_ALIVE_SCRIPT='think' #服务脚本
KEEP_ALIVE_NAME="ChatServer" #你自定义的服务名称
KEEP_ALIVE_PID="${KEEP_ALIVE_DIV}/application/chat/command/${KEEP_ALIVE_NAME}.pid" #服务PID
KEEP_ALIVE_LOG="${KEEP_ALIVE_DIV}/${KEEP_ALIVE_NAME}.log" #服务运行日志 记录错误信息 #判断程序是否已经在运行
status_script(){
ps -fe|grep ${KEEP_ALIVE_SCRIPT}|grep ${KEEP_ALIVE_NAME}|grep -v grep
if [ $? -eq 0 ]
then
echo ${0}' Is running'
running=1 elif [ $? -ne 0 ]
then
echo $0" is NOT running"
running=2
fi
} #启动脚本,先判断脚本是否已经在运行
start_script(){
status_script
if [ ${running} -eq 1 ]
then
echo ${0}' Is starting ...'
else
echo 'start' ${0} '...'
cd ${KEEP_ALIVE_DIV}
nohup ${PHP} ${KEEP_ALIVE_SCRIPT} ${KEEP_ALIVE_NAME}>/dev/null 2>${KEEP_ALIVE_LOG} &
echo $! > ${KEEP_ALIVE_PID}
echo "start finish,PID $!"
fi
} #停止脚本
stop_script(){ status_script
if [ ${running} -ne 1 ]
then
echo ${0}' no starting '$?...
else
PIDS=`ps aux|grep ${KEEP_ALIVE_SCRIPT}|grep ${KEEP_ALIVE_NAME}| grep -v grep |awk '{print $2}'`
for kill_pid in ${PIDS}
do
kill -TERM ${kill_pid} >/dev/null 2>&1
echo "Kill pid ${kill_pid} .."
done
echo 'stop complete'
return 1
fi } #重启脚本
reload_script(){
stop_script
sleep 3
start_script
}
#入口函数
handle(){
case $1 in
start)
start_script
;;
stop)
stop_script
;;
status)
status_script
;;
reload)
reload_script
;;
restart)
reload_script
;;
*)
echo 'KEEP_ALIVE OF THIS SERVER IS '${0} 'status|start|stop|restart';
;;
esac
} if [ $# -eq 1 ]
then
handle $1
else
echo 'KEEP_ALIVE OF THIS SERVER IS '${0} 'status|start|stop|restart';
fi
  • 把文件权限设成 755
  • chmod 755 /etc/init.d/keepalive
  • 设成开机启动
  • chkconfig keepalive on
  • 搞定 试一下
  • service keepalive status
    
    service keepalive start
    
    service keepalive
    
    service keepalive stop

如果你的将服务不稳定,可以把他加到计划任务定时重启 保证后端一直执行

dos2unix shell/keepalive.sh

05-28 03:27