I've searched everywhere and found nothing about this. I'm trying to create a small gauge that shows the CPU usage of one process specified by PID.
I need the command to print a simple answer , hence why top -p $pid isn't good. The command is executed by PHP and needs to print the response immediately.
Something that is closely related to what I need is
sudo ps -p $pid -o %cpu
But after testing and searching some more I found out this prints the average usage since the process started. I need the real time usage from the moment the command si ran, like it shows on top.
Is this possible?
edit::
$cmd = 'sudo sh -c "top -n1 | awk \'/30100/ {print $9}\'"';
echo exec($cmd);
tried without shell
$cmd = "sudo top -n1 | awk '/30100/ {print $9}'";
echo exec($cmd);
still no result, it doesn't echo anything
Best Answer
Well, I would start off with the naive approach like so:
On ubuntu 12.04, it outputs the line for the PID once per update of top:
Then grab the 10th field with awk, although, we don't really need to use grep here. awk can regex for your PID, then print the CPU value: