ps – report process status
本文于2017年3月19號發布在個人博客中,因為個人博客關閉,全部遷移到CSDN,以下是正文:
引言
提到linux ps命令,相信所有在linux開發的程序員都用過
有人是這樣的:
ps -ef | grep httpd
也有人是這樣的:
如果想要了解詳細的信息,請移步:man ps,或者
內容有點多,我英語也不好,說下去會露餡了,進入我們今天的主題:在linux下如何監控進程(包括:狀態,CPU使用率,已使用內存等)?
我做了以下的嘗試:
- 使用第三方庫,python就有psutil
- 通過proc下的stat文件
- 基于linux ps命令
如果沒有各種麻煩的審核流程,第一個可以說是最省事的,第二個是最麻煩的,需要自己解析各個字段并做相應的計算,最終選擇了第三種
/proc/[pid]/stat
第二種我想多說幾句,以上面的httpd進程為例,進程ID:1153,那么在”/proc”目錄下必定有一個”1153″目錄,如下:
$ ls /proc/1153進程狀態相關的信息全在”/proc/1153/stat”文件里了,詳細的可以參考:man proc,直接翻到”/proc/[pid]/stat”章節:
/proc/[pid]/statStatus information about the process. This is used by ps(1).It is defined in the kernel source file fs/proc/array.c.The fields, in order, with their proper scanf(3) formatspecifiers, are listed below. Whether or not certain of thesefields display valid information is governed by a ptraceaccess mode PTRACE_MODE_READ_FSCREDS | PTRACE_MODE_NOAUDITcheck (refer to ptrace(2)). If the check denies access, thenthe field value is displayed as 0. The affected fields areindicated with the marking [PT].(1) pid %dThe process ID.(2) comm %sThe filename of the executable, in parentheses.This is visible whether or not the executable isswapped out.(3) state %cOne of the following characters, indicating processstate:R RunningS Sleeping in an interruptible waitD Waiting in uninterruptible disk sleepZ ZombieT Stopped (on a signal) or (before Linux 2.6.33)trace stoppedt Tracing stop (Linux 2.6.33 onward)W Paging (only before Linux 2.6.0)X Dead (from Linux 2.6.0 onward)x Dead (Linux 2.6.33 to 3.13 only)K Wakekill (Linux 2.6.33 to 3.13 only)W Waking (Linux 2.6.33 to 3.13 only)P Parked (Linux 3.9 to 3.13 only) ......linux ps
同樣只適合在linux操作系統之上,ps命令就比”/proc/[pid]/stat”簡單多了
進程狀態
$ ps --pid $pid -o pid,stat已使用內存(%)
$ ps --pid $pid -o pid,%mem已使用內存(KB)
$ ps --pid $pid -o pid,rssCPU利用率
$ ps --pid $pid -o pid,%cpu根據名稱找pid
$ ps -e -o pid,comm $ ps -e -o pid,cmd
你可能已經發現上面的命令都是具體到某個pid的,但實際場景中我們可能只知道進程名稱不知道進程ID,可以按照如下步驟查找進程名稱對應的進程ID
僅僅通過”ps -e -o pid,comm”是無法區分我是”python comm1.py”還是”python comm2.py”還是”python comm3.py”的,我們需要使用”$ ps -e -o pid,cmd”進行更精確的匹配
子進程
還有一種場景:進程啟動了多個子進程,需要首先找到父進程,然后找出所有的子進程
掌握以上知識,相信你已經能夠編寫出監控進程的代碼了
總結
以上是生活随笔為你收集整理的ps – report process status的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Karaf教程之Config Admin
- 下一篇: 学习Tomcat这一篇就够了