Parsing output of “top” command (Shell) with PHP

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I'm trying to export the output of the "top" command (unix) with PHP. Invoking and reading the command/output is pretty simple using the "exex" function but the question is: is the "top" command output (order, names, etc.) always the same? Or is it related to the distribution I'm using?

Is there any way to parse these information "generally" on UNIX systems?

Thanks in advance

回答1:

You could use ps instead, with arguments -A and -o like so:

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

which would give you the output exactly like you specified when you called the command:

 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 

Arguments:

-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. 

All STANDARD FORMAT SPECIFIERS that you could use, you can find in the man page of ps, but I've copied them also here for convenience:

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



回答2:

As mentioned by Lucas, ps is probably printing what you would expect.

If your Unix flavour is Linux, I think pidstat (from the sysstat package) is better suited for your needs (not to mention, documented in a clearer way, in my opinion).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!