I just wrote the following C++ function to programmatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Am I missing something?
getRAM()
{
FILE* stream = popen("head -n1 /proc/meminfo", "r");
std::ostringstream output;
int bufsize = 128;
while( !feof(stream) && !ferror(stream))
{
char buf[bufsize];
int bytesRead = fread(buf, 1, bufsize, stream);
output.write(buf, bytesRead);
}
std::string result = output.str();
std::string label, ram;
std::istringstream iss(result);
iss >> label;
iss >> ram;
return ram;
}
First, I'm using popen("head -n1 /proc/meminfo")
to get the first line of the meminfo file from the system. The output of that command looks like
MemTotal: 775280 kB
Once I've got that output in an istringstream
, it's simple to tokenize it to get at the information I want. Is there a simpler way to read in the output of this command? Is there a standard C++ library call to read in the amount of system RAM?
freeram
insysinfo
is not what most people would call "free RAM".freeram
excludes memory used by cached filesystem metadata ("buffers") and contents ("cache"). Both of these can be a significant portion of RAM but are freed by the OS when programs need that memory.sysinfo
does contain size used by buffers (sysinfo.bufferram
), but not cache. The best option is to use theMemAvailable
(as opposed toMemFree
) entry in/proc/meminfo
instead. – Carrell