原理:
1)使用ps得到进程名的所有进程pid
ps -C process_name -o pid=
2) 使用 /proc/$pid/status获得内存的占用,并循环求和;
3)使用top获取相关pid的cpu列表,并过滤第10列,求和。
在ubuntu18.04和centos7.9测试:
# !/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 }