Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find total amount of RAM my system has using C

Tags:

c

is there a way to find out the total amount of RAM my system has using C? I am on Ubuntu 12.04. I need to write an application in C that should ideally query the total amount of RAM during run time.

like image 550
Ankur Agarwal Avatar asked Oct 19 '14 06:10

Ankur Agarwal


2 Answers

On Linux, this is available from /proc/meminfo. Example:

MemTotal:       16469432 kB
MemFree:          792136 kB
MemAvailable:   15201832 kB
Buffers:         5806244 kB
Cached:          8637760 kB
...

Just open this as an ordinary file, and parse the contents.

like image 115
Dietrich Epp Avatar answered Sep 23 '22 06:09

Dietrich Epp


The cleanest way is to use procfs (see Dietrich's answer).

However, for more details about the hardware (RAM, CPU count, speed, model numbers, misc other devices) you can extract tons of info from dmesg:

dmesg | grep Memory

You can use the C stdlib popen() to read from dmesg if you have privs, and parse all sorts of info. I have used this for a monitoring system like Spong to extract as much information as possible about the node. You can even monitor it live for feedback from hardware / device commands you issue (dmesg | tail -f).

Keep in mind dmesg isn't always available, depending on privs.

like image 20
codenheim Avatar answered Sep 26 '22 06:09

codenheim