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?
It means that all the processes are stuck waiting... they are "blocked" on thing like user input, network card, hard-drive data, or even ram. Basically it means that the threads are all waiting for the operating system to let them run again.
The ps command, run periodically, displays the CPU time under the TIME column and the ratio of CPU time to real time under the %CPU column. Look for the processes that dominate usage. The au and v options give similar information on user processes. The options aux and vg display both user and system processes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With