I’m writing a little program in C that I want to use to output some system stats to my HD44780 16×2 character display. The system I’ll be working with is a Debian ARM system and, although irrelevant, the display is on the GPIO header.(The system is a Raspberry Pi).
As an initial (somewhat unambitious) attempt, I’d like to start with something simple like RAM and CPU usage (I’m new to C).
I understand that if I make external command calls I need to fork() and execve() (or some equiv that will let me return the results), what I would like to know is how I go about getting the information I want in a nice clean format that I can use.
Surely I will not have to call (for e.g);
free -h
And then use awk or similar to chop out the piece I want? There must be a cleaner way?
The question should be seen as more of a generic, what is best practice for getting info about the system in C (the RAM/CPU usage are just an initial example).
Information about the state of the system is beyond the scope of the C language specification, so anything you do will be specific to the system where your program will run.
Since you’ve identified a target environment (Linux) and a program that provides some of the information you’re after (free(1)
), your best bet would be to acquire and examine the source for that program, learn how it works and use what you’ve learned in your own program. (This would certainly be much better than spawning copies of the utility and picking the output apart.)
1
Give that you’re on a modern Linux system, the information you’re looking for is found in the pseudo-filesystem rooted at /proc/
. Every process has a /proc/[pid]
subdirectory, and other subdirectories provide a global status. E.g. /proc/meminfo
is the source for free(1)
.
2
There are various library routines that provide system information, try taking a look at the sysinfo()
call.