LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Kernel (https://www.linuxquestions.org/questions/linux-kernel-70/)
-   -   How to retrieve CPU, Disk and Memory utilization in linux userspace code (https://www.linuxquestions.org/questions/linux-kernel-70/how-to-retrieve-cpu-disk-and-memory-utilization-in-linux-userspace-code-728588/)

NilesBor 05-26-2009 08:35 AM

How to retrieve CPU, Disk and Memory utilization in linux userspace code
 
Hi,

I would like to write userspace code that will retrieve the CPU utilization, Disk utilization and Memory utilization at a given time (all in %). I know that various linux commands will help (like "top", "free", "mpstat", "sar", etc) but they do not help me when writing C code in userspace as I will not be running commands on the command line.

At first I thought I should investigate what system calls these linux commands make and try to follow similar guide to writing my code to retrieve the utilization parms I mentioned above.

Then, upon further googling, some users say just to use the linux commands in your C code but just precede it by "system" and/or "popen" and parse/retrieve the desired results. Eg:

<code>
system("ps aux | grep 28164 | awk '{print $6}'");
</code>

...prints the 6th field of process ID 28164 (but unfortunately does not store it in a C variable).

<code>
FILE *get_ps;
get_mac = popen("ifconfig eth0 | grep HWaddr | awk '{print $5}'", "r");
</code>

...gets a particular MAC address (stores it in get_mac).


Has anyone had experience doing this? Any recommendations?

Thanks for any help.

sreeharsha.t 06-17-2009 08:13 AM

Quote:

Originally Posted by NilesBor (Post 3553159)
Hi,

I would like to write userspace code that will retrieve the CPU utilization, Disk utilization and Memory utilization at a given time (all in %). I know that various linux commands will help (like "top", "free", "mpstat", "sar", etc) but they do not help me when writing C code in userspace as I will not be running commands on the command line.

The commands like top, free, mpstat, etc. run in userspace.. and the term 'open source' means you can look at their source code.. This will be the easiest way to address your problem..

syg00 06-17-2009 08:27 AM

The data you need are all probably exposed via /proc or sysfs. Simply read from there - some math will be required; that is where calling the above programs is beneficial. Calculating CPU usage (for example) requires determining both a usage and time delta, then doing the math for percentage, taking into account how many processors/cores are in use.


All times are GMT -5. The time now is 07:51 PM.