bofh_of_oz has asked for the wisdom of the Perl Monks concerning the following question:

I've noticed a strange behaviour in my script that reads /proc/meminfo to calculate the amuont of used memory.

The first two lines of /proc/meminfo show something like this (the second line changes all the time):

MemTotal: 125264 kB MemFree: 56996 kB

Below is my code. It opens the file and then keeps reading the two lines and moving the current position back to the beginning (we do not need to close and reopen the file when it changes, right? after all, it works with /proc/stat for CPU stats - see Linux CPU usage monitor)

use strict; use warnings; open(INFIL,"< /proc/meminfo") or die("Unable To Open /proc/meminfo: $! +\n"); while() { my @loads; my $usedmem = 0; for (0,1) { my $in = <INFIL>; (warn "something wrong!\n"), next unless $in =~ /^Mem/; push @loads, ($in =~ /\d+/g)[0]; select (undef, undef, undef, 1) unless $_; } seek INFIL, 0, 0; redo unless defined $loads[0]; $usedmem = ($loads[0] - $loads[1]); print "@loads $usedmem\n"; } close(INFIL);
Well, here's the output of the script:

125264 56716 68548

The last value is correctly calculated from the first two... but let's compare the values that we get by using cat and the script:

cat /proc/meminfo | grep Mem; perl mem.pl

MemTotal: 125264 kB MemFree: 56772 kB 125264 56492 68772

For some reason, I believe those are different...

Ok, let's move the open inside the loop, so that we open and close the file each time. Guess what? same results...

This is driving me nuts... Why does it work with /proc/stat and does not work with /proc/meminfo???

--------------------------------
An idea is not responsible for the people who believe in it...

Replies are listed 'Best First'.
Re: Different result reading meminfo from shell and Perl
by Fletch (Bishop) on Jun 08, 2005 at 20:22 UTC

    Erm, are you confused that the memory free is changing when you're running different commands or what? It's not surprising that there's less memory in use when there's a single perl process running vs having two separate processes going from the shell.

    --
    We're looking for people in ATL

      Yeah, shoud've thought about it... I guess it was due to the lack of caffeine in the system...

      Anyways, it does make sense now, and the code works - thanks for the explanation!

      --------------------------------
      An idea is not responsible for the people who believe in it...