Why doesn't exec(“top”); work on Linux?

空扰寡人 提交于 2019-11-29 15:19:25

Because top is an interactive program that is meant to be run on a terminal, not be executed from a script. You are probably want to run the 'ps' command with arguments which will sort output by cpu utilization. http://www.devdaily.com/linux/unix-linux-process-memory-sort-ps-command-cpu

It probably works, but exec() doesn't return anything. Read the Manual: exec()

$output = null;
exec('top', $output);
echo $output;

But you have another problem: top doesn't exit by itself. You cannot use it here, because you need to send the interrupt-signal (just realized: q is ok too).

One solution is to make top to stop after one iteration

$output = null;
exec('top -n 1', $output);
var_dump($output);

You actually can call top and echo its output. Code that worked for me:

passthru('/usr/bin/top -b -n 1');

-b - running in batch mode

-n 1 - only one iteration

If you want to put it in a variable :

ob_start();
passthru('/usr/bin/top -b -n 1');
$output = ob_get_clean();
ob_clean();

I used:

$cpu = preg_split('/[\s]+/', shell_exec('mpstat 1 1'));
$cpu = 100-$cpu[42];

100% minus the idle time.

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