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...


In reply to Different result reading meminfo from shell and Perl by bofh_of_oz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.