Linux中的top命令是如何實現的?
初探
top是procs
的一部分, 常用來查看系統的負載情況. procs
中除了top外, 還包括ps, free, w, uptime, watch, sysctl
等常用的命令. 了解top命令除了直接在terminal使用之外, 就是top的官方文檔和源代碼了.
不過在此之前, 我們可以用strace top
看下運行top命令時到底做了什么?
- 首先會讀取一系列以依賴文件
- 然后會讀取一些系統配置信息
- 最后就是從
/proc
目錄下讀取進程的statm信息
/proc/xxx/statm
[cal@manjaro-nuc10i7fnh ~]$ cat /proc/self/statm 2126 130 114 6 0 112 0
2126
a)進程占用的總的內存
130
b)進程當前時刻占用的物理內存
114
c)同其它進程共享的內存
6
d)進程的代碼段
0
e)共享庫(從2.6版本起,這個值為0)
112
f)進程的堆棧
0
g)dirty pages(從2.6版本起,這個值為0)
- 關於/proc/xxx/stat的講解可以參考這兩篇博客:
Linux中 /proc/[pid] 目錄各文件簡析
/proc/stat解析
源代碼實現
太久沒碰過C語言了, 看着吃力. 先挖個坑, 先記個參考資料 https://blog.csdn.net/ubuntu2016/article/details/79439658
簡單驗證idle rate的計算邏輯
https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux
https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk65143
使用腳本讀取並計算當前的cpu idle.
[cal@manjaro-nuc10i7fnh ~]$ cat calc_cpu_usage.sh
#!/bin/bash
while :; do
# Get the first line with aggregate of all CPUs
cpu_now=($(head -n1 /proc/stat))
# Get all columns but skip the first (which is the "cpu" string)
cpu_sum="${cpu_now[@]:1}"
# Replace the column seperator (space) with +
cpu_sum=$((${cpu_sum// /+}))
# Get the delta between two reads
cpu_delta=$((cpu_sum - cpu_last_sum))
# Get the idle time Delta
cpu_idle=$((cpu_now[4]- cpu_last[4]))
# Calc percentage
cpu_usage=$((100 * cpu_idle / cpu_delta))
# Keep this as last for our next read
cpu_last=("${cpu_now[@]}")
cpu_last_sum=$cpu_sum
echo "CPU idle rate at $cpu_usage%"
# Wait a second before the next read
sleep 1
done
對比CPU壓力測試前后的idle, 可以確認top的計算方式和上面的腳本一致.
- 沒有壓力測試
stress --cpu 6
stress --cpu 12