perl - 为什么Programming Perl中 "7.2.39 IPC::Open2"所示的程序居然结束了?

标签 perl io ipc stdin child-process

我指的程序是本节显示的第二个程序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 父级。为什么 <STDIN>被评估为假?我知道 perl 评估 <STDIN> 的定义.有点相关的程序

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

没有结束。

最佳答案

在发送 quitbc 后,它终止并关闭了管道的读取端。您的下一个 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";

关于perl - 为什么Programming Perl中 "7.2.39 IPC::Open2"所示的程序居然结束了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63240983/

相关文章:

perl - 如何检测程序是否在 PAR 存档中运行?

perl - 如何创建数据结构的可重复签名?

python - 打印到作为后台进程运行的文件 python 脚本

ruby - 从 ruby​​ IO 中的外部文件读取特定行

c - fork后同步N个兄弟进程

asynchronous - 异步进程调用

bash - 将 stdout 通过管道传输到 Perl 时,如何让它打印换行符?

perl - 我可以使用哪些其他诊断方法来解决这个特定的 Perl 问题?

java - 保持输出流打开

c++ - C++父子进程共享队列