Why do you say sysread won't block? This script does it, by adding the O_NONBLOCK flag to the piped open. top is set to give output every 10 secs, yet the Tk gui is still running fine.
#!/usr/bin/perl
use warnings;
use strict;
use Tk;
my $mw = MainWindow->new(-background => 'gray50');
my $text = $mw->Scrolled('Text')->pack();
my $pid;
my $startb = $mw->Button( -text => 'Start',
-command=> \&work,
)->pack();
my $count = 0;
my $label = $mw->Label(-textvariable=>\$count)->pack();
my $testtimer = $mw->repeat(500,
sub { $count++} );
my $stopb = $mw->Button( -text => 'Exit',
-command=>sub{
kill 9,$pid;
exit;
},
)->pack();
MainLoop;
#####################################
sub work{
$startb->configure(-state=>'disabled');
use Fcntl;
#long 10 second delay between outputs
$pid = open (my $fh, "top -b -d 10 |" ) or warn "$!\n";
fcntl($fh, F_SETFL, O_NONBLOCK) || die "$!\n";
# Set the non-block flags
my $repeater;
$repeater = $mw->repeat(10,
sub {
if(my $bytes = sysread( $fh, my $buf, 1024)){;
$text->insert('end',$buf);
$text->see('end');
}
}
);
}
|