Fix underflow in getFreeMemory()

It actually serves three purposes:
a) Make sure all the values are there (this should be always true, but doesn't hurt making sure) because if SwapFree was there but SwapTotal was not, it'd be a mess
b) add up things in order so we don't underflow, currently the code did process stuff as it came in the file, and it happens that SwapTotal appears before SwapFree in /proc/meminfo so it actually did  "MemFree:" + "Buffers:" + "Cached:" - "SwapTotal:" + "SwapFree:", which can underflow if "MemFree:" + "Buffers:" + "Cached:" < "SwapTotal:"
c) Do not underflow at all, so if  "MemFree:" + "Buffers:" + "Cached:" +  "SwapFree:" < "SwapTotal:" we return 0 correctly not a zillion of free memory

Aurélien you might want to update gwenviews copy of this code (there's a few other bugfixes we did a while ago you didn't update either)

CCMAIL: agateau@kde.org

BUGS: 291129
This commit is contained in:
Albert Astals Cid 2012-06-20 00:33:43 +02:00
parent 791a4ac39e
commit 444e6b7b19

View file

@ -292,19 +292,34 @@ qulonglong DocumentPrivate::getFreeMemory()
qulonglong memoryFree = 0;
QString entry;
QTextStream readStream( &memFile );
static const int nElems = 5;
QString names[nElems] = { "MemFree:", "Buffers:", "Cached:", "SwapFree:", "SwapTotal:" };
qulonglong values[nElems] = { 0, 0, 0, 0, 0 };
bool foundValues[nElems] = { false, false, false, false, false };
while ( true )
{
entry = readStream.readLine();
if ( entry.isNull() ) break;
if ( entry.startsWith( "MemFree:" ) ||
entry.startsWith( "Buffers:" ) ||
entry.startsWith( "Cached:" ) ||
entry.startsWith( "SwapFree:" ) )
memoryFree += entry.section( ' ', -2, -2 ).toULongLong();
if ( entry.startsWith( "SwapTotal:" ) )
memoryFree -= entry.section( ' ', -2, -2 ).toULongLong();
for ( int i = 0; i < nElems; ++i )
{
if ( entry.startsWith( names[i] ) )
{
values[i] = entry.section( ' ', -2, -2 ).toULongLong( &foundValues[i] );
}
}
}
memFile.close();
bool found = true;
for ( int i = 0; found && i < nElems; ++i )
found = found && foundValues[i];
if ( found )
{
memoryFree = values[0] + values[1] + values[2] + values[3];
if ( values[4] > memoryFree )
memoryFree = 0;
else
memoryFree -= values[4];
}
lastUpdate = QTime::currentTime();