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

exec('top', $output) is returning an empty array?

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

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

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);
    }
}

此代码 returns 此输出:

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 是空的?

我尝试了很多方法来将顶级命令的输出作为 $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.