devxlogo

Implementing the GetFreePhysicalMemory API in Linux

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) ;                        }                }        }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist