use Gtk3::Helper; # Handle I/O watchers easily, like Gtk 1.x did $tag = Gtk3::Helper->add_watch ( $fd, $cond, $callback, $data ) $rc = Gtk3::Helper->remove_watch ( $tag )
$tag = Gtk3::Helper->add_watch ( $fd, $cond, $callback, $data )
This method is a wrapper for Glib::IO->add_watch. The callback is called every time when it's safe to read from or write to the watched filehandle.
But aware: you should not use Perl's builtin read and write functions here because these operate always with buffered I/O. Use low level sysread() and syswrite() instead. Otherwise Perl may read more data into its internal buffer as your callback actually consumes. But Glib won't call the callback on data which is already in Perl's buffer, only when events on the the underlying Unix file descriptor occur.
The callback subroutine should return always true. Two signal watchers are connected internally (the I/O watcher, and a HUP watcher, which is called on eof() or other exceptions). Returning false from a watcher callback, removes the correspondent watcher automatically. Because we have two watchers internally, only one of them is removed, but probably not both. So always return true and use Gtk3::Helper->remove_watch to disable a watcher, which was installed with Gtk3::Helper->add_watch.
(Gtk3::Helper could circumvent this by wrapping your callback with a closure returning always true. But why adding another level of indirection if writing a simple ``1;'' at the end of your callback solves this problem? ;)
Example:
# open a pipe to a ls command use FileHandle; my $fh = FileHandle->new; open ($fh, "ls -l |") or die "can't fork"; # install a read watcher for this pipe my $tag; $tag = Gtk3::Helper->add_watch ( $fh->fileno, 'in', sub { watcher_callback( $fh, $tag ); }); sub watcher_callback { my ($fh, $tag) = @_; # we safely can read a chunk into $buffer my $buffer; if ( not sysread($fh, $buffer, 4096) ) { # obviously the connected pipe was closed Gtk3::Helper->remove_watch ($tag) or die "couldn't remove watcher"; close($fh); return 1; } # do something with $buffer ... print $buffer; # *always* return true return 1; }
$rc = Gtk3::Helper->remove_watch ( $tag )
This method removes a watcher, which was created using Gtk3::Helper->add_watch().
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA.