Linux – Get real time CPU usage of linux process with single line command and as a simple result

centoscentos6cpu-usagelinuxmonitoring

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:

$ top |grep %pid

On ubuntu 12.04, it outputs the line for the PID once per update of top:

    username@usrver / $ top |grep 2593
 2593 username   20   0 1103m 170m  16m S   30  2.2  67:25.38 chrome             
 2593 username   20   0 1103m 170m  16m S   28  2.2  67:26.24 chrome             
 2593 username   20   0 1103m 170m  16m S   30  2.2  67:27.15 chrome             
 2593 username   20   0 1103m 170m  16m S   23  2.2  67:27.86 chrome             
 2593 username   20   0 1103m 170m  16m S   25  2.2  67:28.60 chrome

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:

username@usrver / $ top | awk '/2593/ {print $10}'
25
29
30
32