exec('top', $output) 正在返回一个空数组?



我正在编写一个PHP脚本,用于检查系统的CPU使用情况,但它无法按我的意愿工作。

我在stackoverflow上看到了很多类似的问题,但我还没有找到解决我的问题的方法。

public static function checkCurrentCpuUsage()
{
$load = sys_getloadavg();
if (true) {
$output = '';
exec('top', $output, $return_var);
echo "<br>";
echo 'print_r($load) --> ';
print_r($load);
echo "<br>";
echo 'var_dump($output) --> ';
var_dump($output);
echo "<br>";
echo 'print_r($output) --> ';
print_r($output);
echo "<br>";
echo 'print_r($return_var) --> ';
print_r($return_var);
}
}

此代码返回以下输出:

print_r($load) --> Array ( [0] => 0.53 [1] => 0.41 [2] => 0.41 ) 
var_dump($output) --> array(0) { } 
print_r($output) --> Array ( ) 
print_r($return_var) --> 1

为什么$output是空的?

我已经尝试了很多方法来将 top-命令的输出作为 $output 中的数组获取,但没有任何效果。

我找到的一些答案告诉我"exec('top', $output, $return_var(;"会卡在"top-command"中,所以我尝试使用"top -n 1"代替,但这对我不起作用。

我也尝试了很多使用"passthru(("和"shell-exec(("而不是"exec(("的版本,但没有任何效果。

你能告诉我如何将"top-command"的输出作为数组获取吗?

Top 是一个交互式程序,默认情况下将输出发送到视频。 为了获得输出,您可以按照手册页以批处理模式运行它,使用-b-n 1

-b  :Batch-mode operation
Starts top in Batch mode, which could be useful for sending output from top to other  pro‐
grams or to a file.  In this mode, top will not accept input and runs until the iterations
limit you've set with the `-n' command-line option or until killed.

-n  :Number-of-iterations limit as:  -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.

最新更新