I'm having some difficulty with a process monitoring application written in Tk, which reads the output of tail asynchronously. My first attempt at this worked well until the application being monitored spewed lots of text to the log file, which caused the GUI to freeze.
sub component_window {
my ($prch,$pid) = @_;
if (!exists $prch->{window}) {
my ($title) = $prch->{log} =~ m(/(\w+)/logFile);
$prch->{window} = my $newwin = $prch->{widget}->Toplevel( -tit
+le => $title );
my $fr1 = $newwin->Frame;
$fr1->pack( -side => 'top');
$fr1->Label( -text => 'Log File: ')->pack( -side => 'left');
$fr1->Label( -text => $prch->{log})->pack( -side => 'left');
my $fr2 = $newwin->Frame;
$fr2->pack( -side => 'top');
$fr2->Button( -text => 'Close', -command => [$newwin => 'destr
+oy'])
->pack( -side => 'left');
$fr2->Button( -text => 'Kill', -command => sub {system("kill $
+pid")})
->pack( -side => 'left');
$newwin->bind( '<Destroy>' => sub {delete $prch->{window}});
my $txt = $newwin->Scrolled('ROText',
-scrollbars => 'e',
-height => 20,
-setgrid => 'true',
);
$txt->pack( -side => 'top');
$prch->{tailwin} = $txt;
my $tail = Tk::IO->new( -linecommand => sub { tail_lines($prch
+, $_[0]) });
$tail->exec("tail -f $prch->{log}");
}
}
sub tail_lines {
my ($proc,$text) = @_;
print "tail_lines $text" if $debug;
$proc->{tailwin}->insert('end' => $outstr);
$proc->{tailwin}->see('end');
}
My first thought was that the insert and see methods are being called excessively, so I decided to make the program buffer up the text and print it at a convenient point in my polling cycle.
sub tail_lines {
my ($proc,$text) = @_;
print "tail_lines $text" if $debug;
push @{$proc->{tailbuf}},$text;
}
sub check_log {
my $this = shift;
return unless exists $this->{log};
# ... other code here to do with log files
if (exists $this->{tailbuf}) {
my $outstr = '';
$outstr .= shift @{$this->{tailbuf}} while @{$this->{tailbuf}}
+;
$this->{tailwin}->insert('end' => $outstr);
$this->{tailwin}->see('end');
}
}
My application now does not freeze, but instead I get chunks of the log file missing. check_log is called via Tk::repeat.
In Tk's threading model, we thus have two asynchronous threads, one called via Tk::IO that is pushing to the array, and one called from repeat on a polling cycle, which is shifting the text out.
I would expect that shift and push operations on the same array to be atomic, but they are not. Unless I have done something silly in my code :).
Any of you any idea how to achieve what I want? Any suggestions welcome.