管道 pipe 例子

#!/usr/bin/perl -w
use POSIX ":sys_wait_h";
$|=1;
my $read;
my $write;
$SIG{CHLD}=sub {
    my $pid;
    while(($pid = waitpid(-1, &WNOHANG)) > 0) {      
    }  
};

pipe($read,$write) or die("create pipe fail\n");

my ($source_file) =  @ARGV;
open my $src_fh,'<',$source_file;
my @data;
my $i=0;
while(my $src=<$src_fh>)
{

    my $pid = fork();
    if ($pid == 0)
    {
        close($read);
        chomp($src);   

        my $flag = somesub($src);
        print $write "$src $flag\n";
        sleep 1;

        exit;
    }
    else
    {
        close($write);
        while(my $line=<$read>)
        {
            print ++$i,' : ', $line;
            push @data,$line;
        }
        pipe($read,$write) or die("create pipe fail\n");
    }
}
close $src_fh;

open my $fh,'>',"$source_file.result";
print $fh @data;
close $fh;

sub somesub {
    my ($src) = @_;
    my $flag = $src=~/888/ ? 'ok' : 'fail';
    return $flag;
} 


blog comments powered by Disqus

Published

29 January 2013

Tags