Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On linux, how should I calculate the amount of free memory from the information in /proc/mem?

Tags:

linux

memory

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.
like image 334
kdt Avatar asked Sep 22 '09 13:09

kdt


1 Answers

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.

like image 168
Andre Blum Avatar answered Oct 04 '22 04:10

Andre Blum