5

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?

animuson
  • 53,861
  • 28
  • 137
  • 147
genesis
  • 50,477
  • 20
  • 96
  • 125

5 Answers5

8

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

MK.
  • 33,605
  • 18
  • 74
  • 111
8

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

Oleksandr Yanovets
  • 4,661
  • 4
  • 31
  • 26
6

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);
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • I never said anything about `-l 1`. I just tried it myself with `-n 1` and it works fine – KingCrunch Jul 11 '11 at 16:57
  • Look here http://phpcode.eu/exec/index2.php - how is it possible that it does work with classic echo exec(); ? – genesis Jul 11 '11 at 16:58
  • $output = null; exec('top -n 1', $output); print_r($output); //What's wrong here? – genesis Jul 11 '11 at 16:58
  • Without any further information I can't tell anything else then "works fine here". Maybe you need to adjust the path to `top` or something like that (because maybe `$PATH` is not set or something like that). Thats all. And really: Only "Does not work" on nearly every answer does not encourage me to think about it any further. – KingCrunch Jul 11 '11 at 17:25
3

If you want to put it in a variable :

ob_start();
passthru('/usr/bin/top -b -n 1');
$output = ob_get_clean();
ob_clean();
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
0

I used:

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

100% minus the idle time.