2014-04-01 38 views
1

我試圖用PHP導出「top」命令(unix)的輸出。使用「exex」函數調用和讀取命令/輸出非常簡單,但問題是:「top」命令輸出(順序,名稱等)總是相同嗎?或者它與我正在使用的分配有關?用PHP解析「top」命令(Shell)的輸出

有沒有什麼辦法可以在UNIX系統上「一般」解析這些信息?

在此先感謝

+0

那裏有很多非常強大的機器可讀的UNIX工具。如果你描述你真正的想法,你會得到更好的答案。 – kojiro

回答

1

你可以使用PS而是帶有參數-A和-o像這樣:

ps -Ao %cpu,%mem,user,comm 

完全像你指定的,當你調用它會給你的輸出命令:

0.0 0.1 root  udisks-daemon 
0.0 0.0 root  udisks-daemon 
0.0 0.1 root  gdm-simple-slav 
11.0 0.4 root  Xorg 
0.0 0.1 root  NetworkManager 
0.0 0.1 root  polkitd 
0.0 0.1 root  gdm3 

參數:

-A  Select all processes. 

-o format 
       User-defined format. format is a single argument in the 
       form of a blank-separated or comma-separated list, which 
       offers a way to specify individual output columns. The 
       recognized keywords are described in the STANDARD FORMAT 
       SPECIFIERS section below. Headers may be renamed (ps -o 
       pid,ruser=RealUser -o comm=Command) as desired. If all 
       column headers are empty (ps -o pid= -o comm=) then the 
       header line will not be output. Column width will 
       increase as needed for wide headers; this may be used to 
       widen up columns such as WCHAN (ps -o pid,wchan=WIDE- 
       WCHAN-COLUMN -o comm). Explicit width control (ps opid, 
       wchan:42,cmd) is offered too. The behavior of ps -o 
       pid=X,comm=Y varies with personality; output may be one 
       column named "X,comm=Y" or two columns named "X" and "Y". 
       Use multiple -o options when in doubt. Use the PS_FORMAT 
       environment variable to specify a default as desired; 
       DefSysV and DefBSD are macros that may be used to choose 
       the default UNIX or BSD columns. 

所有標準格式說明,你可以使用,你可以找到在PS的man頁面,但我也是在這裏他們複製了方便:

https://gist.github.com/ivankovacevic/9918272

+1

請注意,ps和top不會給出相同的輸出,ps會給出在整個生命週期中的平均使用,根據您的使用情況,ps可能無用。更多信息:https://unix.stackexchange.com/a/58541 – Lucas

0

正如盧卡斯提到,ps可能正在打印你所期望的。如果你的Unix風格是Linux,我認爲pidstat(來自sysstat包)更適合你的需求(更不用說,以更清晰的方式記錄在我看來)。