[Perl] solved: examples of IO::Pipe and IO:Handle
David Baird
david.baird at homemail.com
Tue Oct 29 06:28:38 PST 2002
I found the solution to my problem in the IO::Handle::blocking funtion. Here
is a full example.
It was tested with ActiveState Perl 5.6.1 Build 633 on Windows 2000, with no
additional modules.
I am open to comments on my code.
Thanks,
David Baird
-----------------------------------------------------------
#!/usr/bin/perl -w
use strict;
# For a Tk dialog child with output from the parent process
use Tk;
use Tk::widgets;
use Tk::ROText;
# To create a pipe between parent and child
use IO::Pipe;
my $pipe = new IO::Pipe;
my ($pid, $win, $scroll);
# Create a child Tk dialog
if($pid = fork()) {
# create a non-blocking reading end of the pipe
$pipe->reader();
$pipe->blocking(0);
# Create main window
$win = MainWindow->new;
# Add a Textbox and a Button to main window
$scroll = $win->Scrolled(qw/ROText -height 10 -width 10 -scrollbars
se -wrap none/)
->pack(qw/-fill both -side right -expand y -padx 3/);
$win->Button(-text => 'Quit', -command => [$win => 'destroy'])
->pack;
# upon focus, immediately process incoming characters
$win->bind('<FocusIn>', sub {
my $char;
for ($char = ''; $char ne '~'; $char = $pipe->getc()) {
if ($char ne '') {
$scroll->insert('end', $char);
$scroll->see('end');
}
updateWidgets $win;
}
# the exit character is a '~' which will destroy the
window
$win->destroy;
});
# Spin the message loop
MainLoop;
exit;
}
# Here is the parent, which creates a writer end of the pipe
# and flushes every character
$pipe->writer();
$pipe->autoflush(1);
# Send a number every second to the pipe (the child dialog) and
# print an interesting message to the standard output
for (my $i = 19; $i >= 0; $i -= 1) {
sleep(1);
$pipe->print($i . ' ');
print "value is $i\n";
$pipe->print("\n") if ($i % 10 == 0);
}
# The end, bye bye
sleep(1);
$pipe->print('~');
print "Goodbye\n";
exit;
More information about the Perl
mailing list