How to retrieve CPU, Disk and Memory utilization in linux userspace code
Linux - KernelThis forum is for all discussion relating to the Linux kernel.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
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:
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..
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.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.