I am writing a PHP-Script to be used to check the cpu-usage of my system but it won't work as I want.
I have seen a lot of similar questions here on stackoverflow, but i havent found a solution for my problem yet.
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);
}
}
This code returns this output:
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
Why is $output empty ?
I have tried a lot of things to get the output of the top-command as an array in $output, but nothing worked.
Some answers i found told me that "exec('top', $output, $return_var);" will get stuck in the "top-command", so i tried using "top -n 1" instead but this didn't work for me.
I also tried a lot of versions with "passthru()" and "shell-exec()" instead of "exec()", but nothing worked for me.
Can you tell me how to get the output of the "top-command" as an array?
Top is an interactive program and sends output to video by default.
In order to get the output you can run it in batch mode with -b
and -n 1
, as per man page
-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.
and
-n :Number-of-iterations limit as: -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.