perl – 简单的open3示例不起作用

我正在尝试制作一个主perl脚本,调用子perl脚本并通过管道进行交互.

我为master写了这段代码

#!/usr/bin/env perl

use strict;
use warnings;

use IPC::Open3;

my @children;

for my $i ( 0 .. 4 ) {
    print "Master: " . $i . ",I summon you\n";

    $children[$i] = {};

    $children[$i]->{'pid'} = open3( my $CH_IN,my $CH_OUT,my $CH_ERR,'perl child.pl -i ' . $i );

    $children[$i]->{'_STDIN'}  = $CH_IN;
    $children[$i]->{'_STDOUT'} = $CH_OUT;
    $children[$i]->{'_STDERR'} = $CH_ERR;

    my $line = readline $children[$i]->{'_STDOUT'};
    print $line ;

}

print "Master: Go fetch me the sacred crown\n";

for my $i ( 0 .. 4 ) {
    $children[$i]->{'_STDIN'}->write("fetch the sacred crown\n");
    my $line = readline $children[$i]->{'_STDIN'};
    print $line ;
}

print "Master: Thanks. Now die!!!\n";

for my $i ( 0 .. 4 ) {
    $children[$i]->{'_STDIN'}->write("die !!\n");
    my $line = readline $children[$i]->{'_STDIN'};
    print $line ;
}

而这一个给孩子:

#!/usr/bin/env perl

use Getopt::Long ;

my $cmdline_id ;

Getoptions ('i=s' => \$cmdline_id) ;

my $id = $cmdline_id ;

exit 1 if !defined $id ;

print "I am $id,and I am awaken\n" ;

while(<STDIN>) {
    print STDOUT $id . ': Master ask me to ' . $_ ;

    if ($_ =~ /exit/oi) {
        exit 0 ;
    }
}

但是当我启动大师时,他只是在阅读孩子的回答时挂了.

关于我做错了什么,为什么?

解决方法

你是 suffering from buffering.

在子进程开头附近说$| = 1允许子进程打印而不等待输出缓冲区填满.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...