http://www.perlmonks.org/index.pl?node_id=336856

Description: After starting to do Tk programming, I realized how easy it is to make a lousy design which leaks memory, especially with photo objects. So I got tired of running top and peeking back and forth, or repeatedly running ps.

After looking at all the alternatives, I settled on directly reading from /proc. It seemed to run the best out of all tried methods, which I monitored with strace. Look in the upper left corner.

#!/usr/bin/perl
use warnings;
use strict;
use Tk;

##########################################################
# you can put it in your development programs like this:
# my $memmonitor = 1;
#  if($memmonitor){
#  my $pid = $$;
#    if(fork() == 0){exec("./memmonitor $pid")}
# }
######################################################


my $pid = shift || $$;

my $mw = new MainWindow;
$mw->overrideredirect(1);
my $t = $mw->Label(-text=>'', -bg=>'black', -fg=>'yellow')->pack;

my $id = Tk::After->new($mw,1000,'repeat',\&refresh);

MainLoop;

sub refresh{
      my @size = split "\n", `cat /proc/$pid/status`;
      (my $vmsize) = grep {/VmSize/} @size;
      my (undef,$size) = split "\t",$vmsize;
      $t->configure(-text=>"PID: $pid ->  $size");
      if($size eq ''){Tk::exit}
}

comment on linux memory leak monitor
Download Code
Re: linux memory leak monitor
by duelafn on Mar 17, 2004 at 02:08 UTC
    You might want to change the extraction line so that your code still works for programs over 100MB.
    sub refresh{
          my @size = split "\n", `cat /proc/$pid/status`;
          (my $vmsize) = grep {/VmSize/} @size;
          my ($size)   = $vmsize =~ /VmSize:\s+(.*)$/;   # Changed this
          $t->configure(-text=>"PID: $pid ->  $size");
          if($size eq ''){Tk::exit}
    }
    
 [reply]
d/l code
Re: linux memory leak monitor
by onkhector on Mar 17, 2004 at 03:15 UTC
    You can also monitor programs in (horror!) other languages by doing smething like this:
    my $command = shift;
    my $pid = fork();
    unless (0 == $pid){
      ...Tk code...
    }else{
      exec($command);
    }
    
    You now pass the program name instead of the PID to the script.
 [reply]
d/l code
Re: linux memory leak monitor
by zentara on Mar 17, 2004 at 19:28 UTC
    duelafn said: You might want to change the extraction line so that your code still works for programs over 100MB.
    my ($size)   = $vmsize =~ /VmSize:\s+(.*)$/;    
    
    Good point, I looked at it with a hex editor, and it seems that it should be a tab
      (my $vmsize) = grep {/VmSize/} @size;
       my (undef,$size) = split "\t",$vmsize;
     
    

    I'm not really a human, but I play one on earth. flash japh
 [reply]
d/l code

Back to Snippets Section