#!/bin/bash
phpBin=/usr/bin/php
#日志路径
logPrefix=/datasdc/logs/ysgame/log/startHandleBatch_
logPath=${logPrefix}$(date +"%Y%m%d%H").log
#运行的php页面
phpFileName="/www/_www/ysaaa2/cli.php home/stat/handleAppIDOffset"
grepName="home/stat/handleAppIDOffset"
#shell路径需要和运行shell脚本的路径保持一致
shellFileName="startHandleBatch.sh"
phpShellCount=51

#写日志函数
function funcLog() {
  echo "$(date +"%Y-%m-%d %H:%M:%S") ${1} " >> ${logPath}
}

function restart() {
  if [ -f "/www/_www/ysaaa2/run1.txt" ]; then
    mv /www/_www/ysaaa2/run1.txt /www/_www/ysaaa2/run.txt
  fi
  processCount=`ps aux|grep ${grepName}|grep -v "grep"|wc -l`
  funcLog "php脚本数量：$processCount"
  if [ $processCount == 0 ]; then
    funcLog "重新启动脚本"
    for ((i=0; i<$phpShellCount; i++))
    do
       ${phpBin} ${phpFileName}$i &
    done
  else
      processid=`ps aux|grep ${grepName}|grep -v "grep"|awk '{print $2}'`
              for pid in $processid
              do
                kill -9 $pid
              done

              for ((i=0; i<$phpShellCount; i++))
              do
                ${phpBin} ${phpFileName}$i &
              done
    fi

}

function funcStart() {
  funcLog "执行php代码"
  processCount=`ps aux|grep ${grepName}|grep -v "grep"|wc -l`
  funcLog "php脚本数量：$processCount"
  if [ "$processCount" -lt 51 ]; then
    restart
  else
    funcLog "有php代码在执行,不用重新运行php脚本，继续执行以前的php脚本"
  fi
}

funcLog "==启动同步数据库程序=="

#如果出现其它进程影响统计，可以在此添加过滤（或者执行命令的时候，添加shell文件的绝对路径过滤）
#shellProcessCount=$(ps aux|grep "${shellFileName}"|grep -v "grep"|grep -v "vim"|grep -v "vi"|wc -l)
#funcLog "shell脚本数量：$shellProcessCount"
#processList=`ps aux|grep "${shellFileName}"|grep -v "grep"|awk '{print $2}{print $11}{print $12}'`
#funcLog "当前运行父进程pid:$PPID"
#funcLog "当前运行脚本pid:$$"
#  for proc in $processList
#  do
##    if [ proc != $$ ]; then
##        kill -9 $proc
##    fi
#    funcLog $proc
#  done

funcStart

while true
do
  logPath=${logPrefix}$(date +"%Y%m%d%H").log
  funcLog "检测进程状态"
  processCount=`ps aux|grep ${grepName}|grep -v "grep"|wc -l`
  funcLog "php进程数量：$processCount"
  #进程大于51
  if [ "$processCount" -gt 51 ]; then
    funcLog "检测进程大于51个，结束进程"
    restart
  fi
  #进程小于51
  if [ "$processCount" -lt 51 ]; then
    funcLog "检测进程小于51个，重新启动php执行"
    restart
  fi
  sleep 10
done