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

2019-01-28 10:50发布

I was trying to execute this command

echo exec("top");

and

echo exec("/usr/bin/top");

neither works (returns blank output)

does anybody know why?

5条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-28 10:56

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);
查看更多
祖国的老花朵
3楼-- · 2019-01-28 11:11

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

查看更多
戒情不戒烟
4楼-- · 2019-01-28 11:13

I used:

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

100% minus the idle time.

查看更多
唯我独甜
5楼-- · 2019-01-28 11:18

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

查看更多
爷、活的狠高调
6楼-- · 2019-01-28 11:20

If you want to put it in a variable :

ob_start();
passthru('/usr/bin/top -b -n 1');
$output = ob_get_clean();
ob_clean();
查看更多
登录 后发表回答