#!/bin/bash
phpBin=/usr/bin/php
#日志路径
logPrefix=/datasdc/logs/ysgame/log/localCacheRefresh_
logPath=${logPrefix}$(date +"%Y%m%d%H").log
#运行的php页面
phpFileName="/www/_www/ysgame/apple/localcacherefresh.php"
#shell路径需要和运行shell脚本的路径保持一致
shellFileName="guardAppleScanLocalcacherefresh.sh"
#写日志函数
function funcLog() {
  echo "$(date +"%Y-%m-%d %H:%M:%S") ${1} " >> ${logPath}
}

#function phprun() {
#  cmd=$(/usr/bin/php /www/wwwroot/www.ysgame2.cyy/ysgame/test/index3.php >> /www/wwwroot/www.ysgame2.cyy/shelllog.log 2>&1)
#}
#cmd=$(/usr/bin/php "/www/wwwroot/www.ysgame2.cyy/t.php")
#echo "${cmd}"

function funcStart() {
  funcLog "执行php代码"
  processCount=`ps aux|grep ${phpFileName}|grep -v "grep"|wc -l`

  funcLog "php脚本数量：$processCount"


  if [ "$processCount" -lt 1 ]; then
     ${phpBin} ${phpFileName} &
  else
    funcLog "有php代码在执行,不用重新运行php脚本，继续执行以前的php脚本"
  fi
}

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

funcStart

#trap 'onCtrlC' INT
#function onCtrlC () {
#  processid=`ps -aux|grep phpFileName|grep -v "grep"|awk '{print $2}'`
#  if [ "$processCount" -gt 1 ]; then
#    funcLog "检测进程大于1个，结束进程ID：$processid"
#    kill -9 $processid
#  fi
#  kill -9 ${processid}
#  funcLog "结束进程ID：${processid}"
#  exit
#}



while true
do
  logPath=${logPrefix}$(date +"%Y%m%d%H").log
  funcLog "检测进程状态"
  processCount=`ps aux|grep ${phpFileName}|grep -v "grep"|wc -l`
  processid=`ps aux|grep ${phpFileName}|grep -v "grep"|awk '{print $2}'`
  #进程大于1
  if [ "$processCount" -gt 1 ]; then
    funcLog "检测进程大于1个，结束进程ID：$processid"
    kill -9 $processid
  fi
  #进程小于1
  if [ "$processCount" -lt 1 ]; then
    funcLog "检测进程小于1个，重新启动php执行"
    funcStart
  fi
  funcLog "获取当前PHP进程ID：${processid}"
  sleep 10
done

