[Study] top是如何實現的?


Linux中的top命令是如何實現的?

初探

top是procs的一部分, 常用來查看系統的負載情況. procs中除了top外, 還包括ps, free, w, uptime, watch, sysctl等常用的命令. 了解top命令除了直接在terminal使用之外, 就是top的官方文檔源代碼了.
不過在此之前, 我們可以用strace top看下運行top命令時到底做了什么?

  1. 首先會讀取一系列以依賴文件
  2. 然后會讀取一些系統配置信息
  3. 最后就是從/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)

源代碼實現

太久沒碰過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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM