bhargava_sg bhargava_sg - 1 month ago 6
C Question

top command returns 0% CPU usage when I check my process's CPU usage from within the process

I have written a C program which needs to get its own CPU and memory usage. So I have written something like this:

system("prs_pid=`ps | grep prs-m1 | awk '{print $1}'` \n top -n1 | grep -m1 $prs_pid | \
awk '{print \"prs_cpu:\" $7 \"\\nprs_mem:\" $6}' >> /stats");


My application name is prs and I do a PS and get the pid of my process and then want to get CPU usage from running TOP. The program reports it is using 2% memory and 0% CPU. But, running the same command manually on the cmd returns the same memry usage but a valid non-zero CPU that I can verify by running top. What I don't understand is why is the cpu usage always 0% when tried from inside the system?

Answer

When you're running your system command, the current process is suspended (not sure if it is the proper term, but not running at any rate), waiting for the command you ran to end.

While it's suspended, its CPU usage is 0%, which is expected.

To get the correct information, you have to run your system command in a separate thread or process, so your program can keep running.

Comments