Es posible establecer una comunicación bidireccional usando dos pipes en sentidos opuestos.
lhp@nereida:~/Lperl/src/cookbook/ch16$ cat -n mypipe.pl
1 #!/usr/bin/perl -w
2 use strict;
3 use IO::Handle;
4
5 my ($FROM_CHILD, $TO_FATHER) = (IO::Handle->new(), IO::Handle->new());
6 my ($FROM_FATHER, $TO_CHILD) = (IO::Handle->new(), IO::Handle->new());
7 pipe($FROM_CHILD, $TO_FATHER);
8 pipe($FROM_FATHER, $TO_CHILD);
9 $TO_FATHER->autoflush(1);
10 $TO_CHILD->autoflush(1);
11
12 my $pid;
13
14 if ($pid = fork) {
15 die "cannot fork: $!" unless defined $pid;
16 close $FROM_FATHER; close $TO_FATHER;
17 my $line;
18 chomp($line = <$FROM_CHILD>);
19 print "Father (PID $$) received: <$line>\n";
20 print $TO_CHILD "Hello from Father (PID $$)!\n";
21 close $FROM_CHILD; close $TO_CHILD;
22 waitpid($pid,0);
23 } else {
24 close $FROM_CHILD; close $TO_CHILD;
25 print $TO_FATHER "Hello from Child (PID $$)!\n";
26 my $line;
27 chomp($line = <$FROM_FATHER>);
28 print "Child (PID $$) received: <$line>\n";
29 close $FROM_FATHER; close $TO_FATHER;
30 exit;
31 }
Observe que para evitar la presencia de atascos el proceso hijo
emprende el envío primero (línea 25) y la recepción después
(línea 27) mientras que el padre lo hace a la inversa:
recibe primero (línea 18) y envía a continuación
(línea 20). La ejecución produce la salida:
lhp@nereida:~/Lperl/src/cookbook/ch16$ ./mypipe.pl Father (PID 5032) received: <Hello from Child (PID 5033)!> Child (PID 5033) received: <Hello from Father (PID 5032)!>
Casiano Rodríguez León
