监测单一进程占用cpu.sh

:<<!
cpu防呆设计,当一个进程cpu占用超过99且持续时间超过2分钟,则关闭此进程
shell单行注释用#多行注释用:<<? 注释内容  ?(不一定用?保持一致即可)
!
#!/bin/sh
CUR_PATH=$(cd `dirname $0`; pwd)
if [ -f $CUR_PATH/log ] ;then
mkdir -p $CUR_PATH/log/
fi
log=$CUR_PATH/log/cpu_monit.`date +'%Y-%m-%d'`
#circle脚本另外编写和该脚本放在同一目录下
num=`ps aux| grep circle.sh| grep -v grep| wc -l`
if [[ $num -eq 0 ]];then
sh circle.sh &
echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : the program is not exist start ..." >>$log
fi
#date+'%s'为1970年到现在的秒数 date+'%S'为当前时间的秒,此处要求间隔时间故用S
start_time=`date +'%s'`

while true
do
num=`ps aux| grep circle.sh| grep -v grep| wc -l`
if [[ $num -eq 1 ]];then
pid=`ps aux|grep circle.sh|grep -v grep|awk '{print $2}'`
#echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : the program pid is $pid num is $num" >>$log
cpu_rate=`ps aux|grep circle|grep -v grep|awk '{print $3}'`
if [ `echo "$cpu_rate > 99"|bc` -ne 0 ]; then
    end_time=`date +'%s'`
    dura_time=$(( 10#$end_time-10#$start_time ))
    echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : the cpu_rate is $cpu_rate, dura_time is $dura_time" >>$log
if [[ dura_time -gt 120 ]];then
    kill -9 $pid >> /dev/null
    num=`ps aux| grep circle.sh| grep -v grep| wc -l`
    if [[ $num -eq 0 ]];then
        echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : kill susess!" >>$log
    fi
fi
else
    start_time=`date +'%s'`
    dura_time=0
    echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : cpu_rate is $cpu_rate, less than 95" >>$log

fi
elif [[ $num -gt 1 ]];then
    echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : the program is more than one" >>$log
    exit 1
else
    echo "`date '+%Y-%m-%d %H:%M:%S'` INFO : the program is not exist" >>$log
    exit 1
fi
sleep 1
done
exit 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值