views:

248

answers:

3

On the command line this can be found out using the 'free' utility and 'cat /proc/meminfo'. What would be the different ways to find out the physical RAM size in Linux programatically from a :

  1. Userspace Application
  2. Kernel Module

What API calls are available ?

A: 

cat /proc/meminfo

Nikolai N Fetissov
you just took that from the question :-p
Fredou
Yeh, too little coffee in the morning. But what's wrong with reading and parsing /proc/meminfo from an application?
Nikolai N Fetissov
Absolutely nothing. Reading and parsing from the /proc filesystem is a well-established programmatic interface to the Linux kernel.
Andy Ross
+3  A: 
#include <unistd.h>

long long physical_mem_bytes = (long long) sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);

Other than the command line ulimit, I don't know of a way of finding maximum memory for an individual process.

wallyk
I am not looking for the memory size of a particular process, rather the entire Physical RAM.
vivekian2
Okay, then the code sample is the answer.
wallyk
Note, this may overflow if compiled to a 32 arch and executed on a 64 bit machine, which may have more than 2^32 bytes. Happened to me. Better cast both values to uint64_t or long long.
drhirsch
+1  A: 

Programmatically, Linux won't tell you the actual physical size. Instead you should read this info from SMBIOS. See dmidecode.

Jared Oberhaus
That's a more literal interpretation of the question than I think was intended. It's true that the kernel's visible/usable memory and the amount of physical DRAM on the machine chassis are not required to be the same. But in almost all cases it's the former number that a programmer is interested in.
Andy Ross
From emperical evidence calls to sysconf will give you values such as 2037mb. Using SMBIOS you will get the right answer, such as 2048mb, guaranteed. Further, you can share the code among userspace and kernel code, the parsing is the same.
Jared Oberhaus
But as I pointed out, the kernel may or may not be using that physical memory, even if it is on the board and exposed by the firmware. The proper answer to the question "how much DRAM is available" it to check /proc/meminfo. Your answer is correct only if you are asking a question about hardware configuraiton and not software tuning. My understanding of the context of the question is that is not the case.
Andy Ross
I think Jared's answer makes sense. It does give the exact value. Just that an API call is perhaps not available.
vivekian2