如何使用shell獲取進(jìn)程名的內(nèi)存以及CPU利用率
原理:
1)使用ps得到進(jìn)程名的所有進(jìn)程pid
ps -C process_name -o pid=
2) 使用 /proc/$pid/status獲得內(nèi)存的占用,并循環(huán)求和;
3)使用top獲取相關(guān)pid的cpu列表,并過(guò)濾第10列,求和。
在ubuntu18.04和centos7.9測(cè)試:
# !/bin/bash
# author:robin
# usage: bash proc.sh openresty
if [ -e cpu_mr.log ]
then
rm -f cpu_mr.log
fi
pid_array=(122)
name=$1
if [ -z "$name" ]
then
name="openresty"
fi
#echo $name
#cpucmd: '-p 125 -p 235 -p 568'
cpucmd=''
i=0
#get all pid by proName
funGetPids(){
tempstr=`ps -C $name -o pid=`
#echo $tempstr
for line in $tempstr
do
pid_array[$i]=$line
#echo ${pid_array[$i]}
let "i++"
cpucmd=${cpucmd}" -p $line "
done
return
}
funGetPids
if [ $i -eq 0 ]
then
echo "{\"sum_vmrss\": -1, \"sum_cpu\": -1 }"
exit 0
fi
sum_vmrss=0
sum_cpu=0.0
#compute mem sum
for pid in ${pid_array[@]}
do
vmrss_temp=`cat /proc/$pid/status|grep -e VmRSS|tr -d [:blank:][:alpha:][:]`
#echo 'vmrss_temp= ' $vmrss_temp
sum_vmrss=`expr $sum_vmrss + $vmrss_temp`
done
#echo $cpucmd
tempstr=`top -n 1 $cpucmd |tail -n +8 | awk '{print $10}'`
for line in $tempstr
do
#echo $line
sum_cpu=$(echo "$sum_cpu+$line"|bc)
done
# echo "-------------------"
echo "{\"sum_vmrss\": $sum_vmrss, \"sum_cpu\": $sum_cpu }"
exit
使用方法:
bash proc.sh gnome-shell
輸出json:
{"sum_vmrss": 423712, "sum_cpu": 6.7 }
總結(jié)
到此這篇關(guān)于如何使用shell獲取進(jìn)程名的內(nèi)存以及CPU利用率的文章就介紹到這了,更多相關(guān)shell獲取進(jìn)程名內(nèi)存內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信