![不使用top如何取得top給出的系統任務摘要?](https://rvso.com/image/122434/%E4%B8%8D%E4%BD%BF%E7%94%A8top%E5%A6%82%E4%BD%95%E5%8F%96%E5%BE%97top%E7%B5%A6%E5%87%BA%E7%9A%84%E7%B3%BB%E7%B5%B1%E4%BB%BB%E5%8B%99%E6%91%98%E8%A6%81%EF%BC%9F.png)
top 在其摘要中顯示這些數字:
任務:總共 193 個,1 個正在運行,192 個正在睡覺,0 個停止,0 個殭屍
我正在尋找一種方法來以其他方式獲取它們——運行程式、解析 /proc 檔案。
您知道獲得這些數字的方法嗎?
我能得到的最接近的是:
pgrep "" -c
192
以及頂部和 pgrep:
top -b -n 1 | head -n 2 | tail -n 1; pgrep "" -c
從來不同意...
例如 194 與 191
grep 'procs' /proc/stat
procs_running 2
procs_blocked 0
這裡也提到了跑步、睡覺、停止、殭屍: http://procps.cvs.sourceforge.net/viewvc/procps/procps/top.c?revision=1.134&view=markup#l1025
這個 grep 找到了一個符合項,sleeping 是 192:
grep -R sleeping /proc/*/status | wc -l
但它的 sleep 方式和 pgrep 的 Total 方式並不相符:
top -b -n 1 | head -n 2 | tail -n 1; pgrep "" -c; grep "procs" /proc/stat; grep -R sleeping /proc/*/status | wc -l
答案1
ps -eo stat | awk '/^S/ { stat+=1 } /^R/ { run +=1 } /^Z/ { zomb+=1 } { tot+=1 } END { print "sleeping = "stat" Running = "run" Zombie = "zomb" total = "tot }'
這將為您提供有關進程狀態資訊的相同資訊。
R 將是正在運行的進程,S 將是休眠進程,Z 將是殭屍進程。
請記住,top 總是會多顯示一個正在執行的進程,因為它將考慮 top 的實際運作情況。
答案2
除了幾個例外, ps 會回傳正確的答案。
local output=$(ps axo stat=)
cpu_tasks_running=$(echo -e "${output}" | grep -c '^R')
cpu_tasks_sleeping=$(grep sleeping /proc/*/status | wc -l)
# searching /proc gets better results than searching ps output:
# cpu_tasks_sleeping=$(echo -e "${output}" | grep -cE '^D|^S')
cpu_tasks_stopped=$(echo -e "${output}" | grep -ci '^T')
cpu_tasks_zombie=$(echo -e "${output}" | grep -c '^Z')
cpu_tasks_total=$(($cpu_tasks_running + $cpu_tasks_sleeping))
# counting ps total lines never matched ps running + ps sleeping, nor top
# replaced with math: ps running + ps sleeping
# cpu_tasks_total=$(echo -e "${output}" | wc -l)