Implementing the GetFreePhysicalMemory API in Linux

Because everything in Linux is composed of files, you can get any required information from the /proc/meminfo file. Here’s the code:

int getFreePhysicalMemory(){        ifstream meminfo("/proc/meminfo");        if ( ! meminfo.is_open() )        {                return -1;        }        char szTmp[256];        char szMem[256];        string s0("MemFree:");        string s1("kB");        while ( ! meminfo.eof() )        {                meminfo.getline( szTmp, 256 );                string s2(szTmp);                string::size_type pos0 = s2.find(s0);                if( pos0 != string::npos )                {                        string::size_type pos1  = s2.find(s1);                        if ( pos1 != string::npos )                        {                                string s3 = s2.substr( pos0 + s0.size(), pos1 - (pos0+s0.size()) );                                strncpy(szMem, s3.c_str(), s3.size() );                                return (atoi(szMem)*1024*1024) ;                        }                }        }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: