pipe(FROM_PARENT, TO_CHILD)   or die "pipe: $!";
pipe(FROM_CHILD, TO_PARENT)   or die "pipe:$!";
select((select(TO_CHILD), $| = 1))[0]);      # 自动刷新
select((select(TO_PARENT), $| = 1))[0]);   # 自动刷新

if ($pid = fork) {
        close FROM_PARENT; close TO_PARENT;
        print TO_CHILD "Parent Pid $$ is sending this\n";
        chomp($line = <FROM_CHILD>);
        print "Parent Pid $$ just read this: `$line'\n";
        close FROM_CHILD; close TO_CHILD;
        waitpid($pid, 0);
} else {
        die "cannot fork: $!" unless defined $pid;
        close FROM_CHILD; close TO_CHILD;
        chomp($line = <FROM_PARENT>);
        print "Child Pid $$ just read this: `$line'\n";
        print TO_PARENT "Child Pid $$ is sending this\n";
        close FROM_PARENT; close TO_PARENT;
        exit;
}

 

#!/usr/bin/perl
use strict;
use POSIX ":sys_wait_h";
use Data::Dumper;
my %hash;
print "start\n";
my $count=3;


pipe(READER,WRITER) or die "pipe error $!";

while($count--){
        my $pid=fork();

        if($pid){
                print "In parent\n $$   -- $pid\n";
                $hash{$pid}=1;
        }else{
                close READER;
                open(STDOUT,">&WRITER");
                #sleep 4;
                srand();
                my $sltime = 8*rand();
                sleep $sltime;
                print "In child $$ return value $sltime\n";
                exit 0;
        }

}
close WRITER;


while(scalar(keys(%hash))>0){
        sleep 1;
        print Dumper \%hash;
        while ((my $collect = waitpid(-1,WNOHANG)) > 0) {
                print "$collect exit\n";
                delete $hash{$collect};
        }

}

while(<READER>){
        print Dumper $_;
}
 

[root@test1 fork]# perl test.pl
start
In parent
 11359   -- 11360
In parent
 11359   -- 11361
In parent
 11359   -- 11362
$VAR1 = {
          '11360' => 1,
          '11362' => 1,
          '11361' => 1
        };
11361 exit
11362 exit
$VAR1 = {
          '11360' => 1
        };
$VAR1 = {
          '11360' => 1
        };
$VAR1 = {
          '11360' => 1
        };
$VAR1 = {
          '11360' => 1
        };
$VAR1 = {
          '11360' => 1
        };
11360 exit
$VAR1 = 'In child 11361 return value 0.727502020665298
';
$VAR1 = 'In child 11362 return value 1.97574310994972
';
$VAR1 = 'In child 11360 return value 6.72100603266884
';