脚本计算后台程序消耗资源

脚本计算node_exporter在服务器上消耗的cpu和内存

#!/bin/bash
logfile=node_log.txt
PID=$(ps aux| grep node_exporter | grep -v 'grep' | awk '{print $2}')

while [ "PID" != "" ]
do
    cpu=$(ps aux| grep node_exporter | grep -v 'grep' | awk '{print $3}')
    cpu_count=$(ps aux| grep node_exporter | grep -v 'grep' | awk '{print $3}'|awk -F "." '{print $1}')
    mem=$(ps aux| grep node_exporter | grep -v 'grep' | awk '{print $4}')
    mem_count=$(ps aux| grep node_exporter | grep -v 'grep' | awk '{print $4}'|awk -F "." '{print $1}')
    #echo "cpu=$cpu,mem=$mem"
    if [[ $cpu_count -ge 1 || $mem_count -ge 1 ]]
    then
        localtime=`date "+%Y-%m-%d_%H:%M:%S"`
        echo "cpu=$cpu;mem=$mem ------- time:$localtime" >> $logfile
        sleep 5
    fi
done

注释

cpu_count和mem_count是去除小数点以及后面的数字,方便比较
这里取1为比较基准值,记录cpu和内存大于等于1的时间

终止后台运行的脚本

[root@yx01 cron_task]# fg
./node.sh
^C
[root@yx01 cron_task]# 

或者

[root@yx01 cron_task]# ps aux|grep node.sh
root     15973  0.0  0.0 113288  1464 pts/1    S    12:25   0:00 /bin/bash ./node.sh
root     16541  0.0  0.0 112812   984 pts/1    S+   12:26   0:00 grep --color=auto node.sh
[root@yx01 cron_task]# kill -9 15973
[root@yx01 cron_task]# 
[1]+  Killed                  ./node.sh

猜你喜欢

转载自blog.csdn.net/qq_28686911/article/details/114826323