5

There are many fields in /proc/mem: I know that I can't just take "MemFree", because lots of memory is actually cached. So the question is, how can I calculate the amount of free memory?

Assumptions:

  • The system is configured with no swap space.
  • My definition of "free memory" is that malloc starts failing when this hits zero.
kdt
  • 27,905
  • 33
  • 92
  • 139
  • 1
    The reason why there is no field for the free memory is that it’s mostly a useless metric: it’s not how much memory you have left, it’s what you use it for. Lots of free memory does *not* guarantee anything, be it the number of processes you can start or any kind of performance. – Bombe Sep 22 '09 at 13:56

7 Answers7

8

If as you say the system is configured with no swap space, then the amount of free memory can be calculating by adding the "MemFree", "Buffers" and "Cached" values from /proc/meminfo.

This is exactly what the command 'free -m' shows under 'free' in the '-/+ buffers/cache' line.

In Python, I would implement this as follows:

 with open('/proc/meminfo', 'rt') as f:
        vals = {}
        for i in f.read().splitlines():
            try:
                name, val = i.split(':')
                vals[name.strip()] = int(val.split()[0])
            except:
                pass

 memfree = vals['MemFree'] + vals['Buffers'] + vals['Cached']

This would give a value in kilobytes.

As others have said, malloc is not likely to return null ever. Linux will overallocate and when you start using a page that really cannot be found, the OOM killer will kick in.

Andre Blum
  • 391
  • 3
  • 6
5

I have the feeling you're going down the wrong path. What do you want to do with that information? Do you want to see if you can allocate enough memory for the next operation? If so, you can call malloc and check its return value. If it returns null, the memory wasn't avialable.

Note that memory is a highly dynamic resource. Even your act of opening/closing the /proc filesystem might lead to memory overhead. Even if you somehow do manage to get the amount you could allocate with malloc(), noone can guarantee that the same amount of memory is available the split-second you try to allocate it.

soulmerge
  • 73,842
  • 19
  • 118
  • 155
  • As smcameron describes, malloc will overallocate on many systems, and will never return null. It will just fail when you really start using pages. Also: there may be good reasons to want to check the memory status. For example: if you write a server or service which more or less linearly scales with the amount of sessions you initiate or accept, by watching your free memory, you can stop accepting new sessions, thus preventing existing sessions to break or the OOM killer doing nasty unpredictable stuff with the server itself. – Andre Blum Nov 08 '12 at 13:59
4

Use the source luke!

free.c -- the source for the 'free' command line utility
sysinfo.c -- see the method meminfo() for an example of how /proc/meminfo is read in.

Whilst reading /proc is pretty straight forward being able to predict whether malloc is going to fail is not at all easy. As others have mentioned issues such as overcommit muddy the issue. The standard approach is to just try and allocate what you need and if you can't have it fail gracefully or work with less.

This series of articles is worth reading if you have enough time: What every programmer should know about memory.

chillitom
  • 24,888
  • 17
  • 83
  • 118
  • Excellent answer. In my experience, the +/- buffers/cache line in the output of the 'free -m' command line utility gives a good indication of how close the system is to swapping. This answer taught me how to get that info myself from /proc/meminfo, saving me expensive forks in the periodically refreshing Django dashboard page I am displaying a memory gauge in. – Andre Blum Nov 06 '12 at 17:05
  • Gentleman. Forcing me to go off and learn how to do it the hard way, and now I appreciate the answer even more! – David K May 27 '13 at 13:43
2

AFAIK, malloc will overcommit by default on linux, so malloc won't fail when you might expect it to. You won't see things fail until you actually touch the memory you malloced, and the OOM killer may be awakened.

This may be of interest (no idea how accurate it is.)

http://opsmonkey.blogspot.com/2007/01/linux-memory-overcommit.html

but googling around for linux malloc overcommit will likely turn up some interesting stuff.

smcameron
  • 1,307
  • 8
  • 8
1

The following program calculate memory usages in a Linux environment.

{
FILE *fp;
char tmpline[1024];
char key[1024];
int line = 0;
int num1 = 0;
int num2 =0;
int val = 0;
int cat = 0;
fp = fopen("/proc/meminfo","r");

fgets(tmpline,256,fp);
sscanf(tmpline,"%*s %d\n",&num1);

fgets(tmpline,256,fp);
sscanf(tmpline,"%*s %d\n",&num2);

printf("toatl mem = %d\n free mem = %d\n",num1,num2);

  val = num1-num2;
printf("Used Mem =%d\n",val );

cat = val*100/num1;
printf("per = %d%\n",cat);

fclose(fp);
return(0);
}
jrouquie
  • 4,315
  • 4
  • 27
  • 43
1

Try taking a look at the answers to this previous question.

Community
  • 1
  • 1
Martin
  • 5,119
  • 3
  • 18
  • 16
0

To make an answer to this old post Because I came to this Question again.

free command has and entry "available" /proc/meminfo "MemAvailable"

And man documentation says:

available Estimation of how much memory is available for starting new applications, without swapping. Unlike the data provided by the cache or free fields, this field takes into account page cache and also that not all reclaimable memory slabs will be re‐claimed due to items being in use (MemAvailable in /proc/meminfo, available on kernels 3.14, emulated on kernels 2.6.27+, otherwise the same as free)

Tulan
  • 11
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 08 '22 at 15:08