Re: Gtk::Gdk::input_add and CPU racing



David wrote:

sub list{
      while(<LS>)
      { $text->insert( $font, undef, undef, $_ );}
}
##########################################

My problem is when the command is done my cpu starts to race.  I am not
sure where or how to close the IO.

Any help here would sure be appreciated.  

You need to remove the Gtk input handler when you're done with it. 
Gtk::Gdk->input_add() returns a tag, which you have to pass to  
Gtk::Gdk->input_remove() to remove it. So your code should look like 
this:

  my $id = Gtk::Gdk->input_add(fileno(LS),['read'],\&list);

  sub list{
    while(<LS>)
    { $text->insert( $font, undef, undef, $_ );}
    Gtk::Gdk->input_remove($id);
  }

But beware that the "while (<LS>)" will block your application. Your 
handler gets called, if you can read from the filehandle. You should 
read exactly one line there. Gtk will call your handler again, if more 
data is available, and in the meantime it can render the GUI or handle 
other events.

In fact your handler doesn't work as expected. It's called, if the first
ls output line is available, slurps the whole output it (while the Gtk 
GUI is blocked) or even blocks it for longer if the command sleeps 
without generating any output. The multi-threading effect isn't there.

A good ideom for monitoring output of external app's is this: (I 
copy'n'paste from an older posting of mine, where someone wanted to 
monitor mplayer's output)

--snip--

  sub playmovie {
    my ($file) = @_;

    my $fh = FileHandle->new;

    open($fh, "mplayer $file |") or die "can't fork mplayer";

    my $handle;

    $handle = Gtk::Gdk->input_add (
      $fh->fileno, 'read',
      sub { got_mplayer_output( $fh, $handle ) }
    );

    1;
  }

  sub got_mplayer_output {
    my ($fh, $handle) = @_;

    if ( eof($fh) ) {
      # mplayer exit
      Gtk::Gdk->input_remove($handle);
      close $fh;
      print "mplayer:exit\n";
      return 1;
    }

    my $line = <$fh>;
    print "mplayer:$line";

    1;
  }

--snip--

Note: your handler gets called also when the program exits. That's why 
it first checks eof($fh) and cleans up everything if this is true.

Hope this helps.

Regards,

Joern

-- 
LINUX - Linux Is Not gnU linuX




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]