Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Dec 20, 2005

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

Elsayed Elghadban
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap