我正在尝试编写一个 bash 脚本来读取每个进程的 cpu 使用情况。但是,我认为我做错了。当我测试这个脚本时,它给了我一个不正确的百分比。继承人的代码:
prev_total=0
prev_idle=0
prev_processtotal=0
prev_utime=0
while true; do
cpu=`cat /proc/stat | head -n1 | sed 's/cpu //'`
user=`echo $cpu | awk '{print $1}'`
system=`echo $cpu | awk '{print $2}'`
nice=`echo $cpu | awk '{print $3}'`
idle=`echo $cpu | awk '{print $4}'`
wait=`echo $cpu | awk '{print $5}'`
irq=`echo $cpu | awk '{print $6}'`
srq=`echo $cpu | awk '{print $7}'`
zero=`echo $cpu | awk '{print $8}'`
total=$(($user+$system+$nice+$idle+$wait+$irq+$srq+$zero))
diff_idle=$(($idle-$prev_idle))
diff_total=$(($total-$prev_total))
usage=$(($((1000*$(($diff_total-$diff_idle))/$diff_total+5))/10))
process=`cat /proc/20966/stat`
utime=`echo $process | awk '{print $14}'`
stime=`echo $process | awk '{print $15}'`
cutime=`echo $process | awk '{print $16}'`
cstime=`echo $process | awk '{print $17}'`
processtotal=$(($utime+$stime+$cutime+$cstime))
diff_processtotal=$(($processtotal-$prev_processtotal))
diff_utime=$(($utime-$prev_utime))
processusage=$(($((1000*$(($diff_processtotal-$diff_utime))/$diff_processtotal+5))/10))
clear
echo "total cpu usage: $usage%"
echo "one selected process: $processusage%"
prev_total=$total
prev_idle=$idle
prev_processtotal=$processtotal
prev_utime=$utime
sleep 1
done
我有点迷路了,所以非常感谢任何帮助:)