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

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

Assumptions:

  • The system is configured without swap space.
  • My definition of "free memory" is that malloc crashes when it reaches zero.
+5
source share
6 answers

Use the source luke!

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

/proc , , malloc , . , , overcommit muddy the issue. , , , .

, : .

+4

, , , "MemFree", "Buffers" "Cached" /proc/meminfo.

, "free -m" "free" "- + + buffers/cache".

Python :

 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']

.

, malloc null. Linux , , , OOM .

+7

, . ? , ? , malloc . null, .

: . / /proc . - , malloc(), , split-second .

+5

AFAIK, malloc linux, malloc , . , , malloced, OOM .

( , ).

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

but a googling search for overflowing linux malloc is likely to generate interesting stuff.

+2
source

Try looking at the answers to this previous question.

+1
source

The following program calculates memory usage 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);
}
+1
source

All Articles