【问题标题】:Why does the program shown in "7.2.39 IPC::Open2" of Programming Perl actually ends?为什么Perl编程的“7.2.39 IPC::Open2”中显示的程序实际上结束了?
【发布时间】:2020-11-24 04:50:21
【问题描述】:

我指的程序是本节中显示的第二个程序here。它的一个小修改是:

#!/usr/bin/perl -w
use IPC::Open2;
use Symbol;

$WTR = gensym();  # get a reference to a typeglob
$RDR = gensym();  # and another one

$pid = open2($RDR, $WTR, 'bc');
print "$pid\n";

while (<STDIN>) {           # read commands from user
    print $WTR $_;          # write a command to bc(1)
    $line = <$RDR>;         # read the output of bc(1)
    print STDOUT "$line";   # send the output to the user
}

这个程序运行正常。说它的名字是 prop_7_2_39_2.pl,那么与它的典型交互是:

>./prop_7_2_39_2.pl
75955
2+2
4
quit

>

也就是说,在输入“quit”之后,子进程bc 就失效了,之后我需要输入一个换行符才能真正完成 perl 父进程。为什么&lt;STDIN&gt; 被评估为假?我知道 perl 评估 &lt;STDIN&gt; 的定义。有点相关的程序

#!/usr/bin/perl -w
while(<STDIN>){}

没有结束。

【问题讨论】:

    标签: perl io ipc stdin child-process


    【解决方案1】:

    在将quit 发送到bc 后,它会终止,从而关闭管道的读取端。您的下一个 print $WTR $_ 将失败并生成终止程序的 SIGPIPE 信号 - 除非您为其安装信号处理程序。

    另一种解决方案可能是在您成功发送内容后检查从bc 的读取:

    while (<STDIN>) {              # read commands from user
        print $WTR $_;             # write a command to bc(1)
        my $line = <$RDR>;         # read the output of bc(1)
    
        if($line) {
            print STDOUT "$line";  # send the output to the user
        } else {
            last;                  # break out of the while loop
        }
    }
    print "Controlled ending...\n";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2012-08-14
      • 1970-01-01
      • 2021-04-03
      • 2012-04-30
      • 2010-11-06
      • 2016-09-06
      • 1970-01-01
      相关资源
      最近更新 更多