简体   繁体   中英

How to find out the amount of free physical memory under linux (in c)

Assume I want to cache certain calculations, but provoking syncing it out to disk would incur an I/O penalty that would more than defy the whole purpose of caching.

This means, I need to be able find out, how much physical RAM is left (including cached memory, assuming I can push that out and allowing for some slack should buffering increase). I looked into /proc/meminfo and know how to read it out. I am not so sure how to combine the numbers to get what i want though. Code not necessary, once i know what I need I can code it myself.

I will not have root on the box it needs to run at, but it should be reasonably quiet otherwise. No large amount of disk I/O, no other processes claiming a lot of mem in a burst. The OS is a rather recent linux with overcommitting turned on. This will need to work without triggering the OOM killer obviously.

The Numbers don't need to be exact down to the megabyte, I assume that it'll be roughly in the 1 to 7 gib range depending on the box but getting close to about 100 mb would be great.

It'd definitely be preferable if the estimate were to err on the smallish side.

Unices have the standard sysconf() function ( OpenGroups man page , Linux man page ).

Using this function, you can get the total physical memory:

unsigned long long ps = sysconf(_SC_PAGESIZE);
unsigned long long pn = sysconf(_SC_AVPHYS_PAGES);
unsigned long long availMem = ps * pn;

作为H2CO3答案的替代方案,您可以从/ proc / meminfo中读取。

For me, statfs worked well.

#include <sys/vfs.h>

struct statfs buf;
size_t available_mem;
if ( statfs( "/", &buf ) == -1 ) 
    available_mem = 0;
else 
    available_mem = buf.f_bsize * buf.f_bfree;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM