【问题标题】:Simple open3 example not working简单的open3示例不起作用
【发布时间】:2012-07-01 04:42:09
【问题描述】:

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

我已经为大师写了这段代码:

#!/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 ;
    }
}

但是当我启动 Master 时,他只是在阅读孩子的回复时挂起。

知道我做错了什么,为什么?

【问题讨论】:

    标签: perl ipc ipcopen3


    【解决方案1】:

    你是suffering from buffering

    在子进程开始附近说$|=1,以允许子进程打印而无需等待输出缓冲区填满。

    【讨论】:

      【解决方案2】:

      作为旁注,将 undef 传递给第三个参数(就像你一样)不会做你想要的。您需要使用 Symbol 的 gensym 初始化变量。

      use Symbol qw( gensym );
      
      my %child;
      $child{pid} = open3(
          $child{'_STDIN' } = gensym,
          $child{'_STDOUT'} = gensym,
          $child{'_STDERR'} = gensym,
          'perl', 'child.pl', '-i' => $i
      );
      
      $children[$i] = \%child;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-23
        • 2016-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多