#!/usr/bin/bash
#Monitor script.
WORKDIR="${HOME}"
SCRIPTNAME=(run.py)
SCRIPTCOUNT=${#SCRIPTNAME[*]}
prcidcount=`expr $SCRIPTCOUNT - 1`
LOG_FILE="$WORKDIR/data/log/mon.log"
FLG_FILE="$WORKDIR/data/log/.flg"
SCRIPT_PATH="$WORKDIR"
cur_datemsg=`echo $(date '+%Y-%m-%d')`
#
#
logcreate()
{
echo "================================================================================" >> $LOG_FILE
echo "$cur_datemsg" >> $LOG_FILE
echo "$cur_datemsg" > $FLG_FILE
echo "================================================================================" >> $LOG_FILE
}
if [ -d $WORKDIR/data/log ]
then
echo "logs dir already there." >> /dev/null
else
mkdir -p $WORKDIR/data/log
logcreate
fi
#
#
if [ -f $LOG_FILE ]
then
file_size=`ls -l $LOG_FILE | awk '{print $5}'`
else
touch $LOG_FILE
logcreate
file_size=0
fi
if [ $file_size -ge 10485760 ]
#if [ $file_size -ge 104 ]
then
mv $LOG_FILE $WORKDIR/log/.mon_named.log.$cur_datemsg
rm $LOG_FILE
logcreate
fi
OS_Type=`uname`
for ins in `seq 0 $prcidcount`;
do
#
#echo ${SCRIPTNAME[$ins]}
if [ $OS_Type == "Linux" ]
then
PID=`ps -ef | grep -v vi | grep -v tail | grep ${SCRIPTNAME[$ins]} | grep -v grep |grep "\<${USER}\>"| awk '{print $2}'`
#echo "[$(date '+%Y-%m-%d %H:%M:%S')]:$OS_Type , Script ${SCRIPTNAME[$ins]} already running pid is $PID" >> $LOG_FILE
fi
if [ x${PID} == "x" ]
then
echo "[$(date '+%Y-%m-%d %H:%M:%S')]: Auto script ${SCRIPTNAME[$ins]} is not running, restart it!" >> $LOG_FILE
case $OS_Type in
"Linux")
$SCRIPT_PATH/${SCRIPTNAME[$ins]} & >/dev/null 2>/dev/null >> $LOG_FILE
sleep 3
;;
*)
echo "[$(date '+%Y-%m-%d %H:%M:%S')]: OS type $OS_Type is not supported!" >> $LOG_FILE
;;
esac
if [ $OS_Type == "Linux" ]
then
echo ${SCRIPTNAME[$ins]}
XPID=`ps -ef | grep -v vi | grep -v tail | grep ${SCRIPTNAME[$ins]} | grep -v grep | grep "\<${USER}\>"| awk '{print $2}'`
fi
if [ x${XPID} == "x" ]
then
echo "[$(date '+%Y-%m-%d %H:%M:%S')]: Auto script ${SCRIPTNAME[$ins]} cannot be started! Please check!" >> $LOG_FILE
else
echo "[$(date '+%Y-%m-%d %H:%M:%S')]: Auto script ${SCRIPTNAME[$ins]} is running now! The PID is $XPID" >> $LOG_FILE
fi
fi
done
使用定时任务(定时时间自行配置),比如一分钟检查一次进行使用,有看不明白的可以私信我:
* * * * * /usr/bin/bash /www//script/monitor.sh &> /dev/null
脚本工作原理:
定时任务执monitor.sh脚本, 脚本里面检查需要守护的进程是否存在,存在则跳过,不存在则拉起来。