当我执行以下 IPC::Open3 概要时 (https://perldoc.perl.org/IPC::Open3):
# send STDOUT and STDERR to already open handle
open my $outfile, '>>', 'output.txt' or die "open failed: $!";
my $pid = open3('<&STDIN', $outfile, undef, 'ls');
waitpid($pid, 0);
为什么“output.txt”中没有输出?
当将打开的文件句柄作为 in 或 out 参数之一给出时,
IPC::Open3
(和 IPC::Open2
)的行为在文档中描述得很少。当您仅将文件句柄作为 chld_out
或 chld_err
传递时,当前打开的任何内容都会被关闭,并且它会被重用为管道的读取端(写入端连接到执行进程的标准输出或标准错误) 。相对的两端用于 chld_in
。
演示:
#!/usr/bin/env perl
use v5.36;
use IPC::Open3;
# send STDOUT and STDERR to already open handle
open my $outfile, '>>', 'output.txt' or die "open failed: $!";
say '$outfile is a file handle' if -f $outfile;
my $pid = open3('<&STDIN', $outfile, undef, 'ls');
if (-f $outfile) {
say '$outfile is still a file';
} elsif (-p _) {
say '$outfile is now a pipe handle';
}
say scalar readline($outfile); # First file in directory
waitpid $pid, 0;
产生输出:
$outfile is a file handle
$outfile is now a pipe handle
a file name
如果您使用输出参数的
>&HANDLE
版本,将句柄的底层文件描述符作为 HANDLE 传递,则会将其用作执行进程的标准输出:
my $pid = open3('<&STDIN', sprintf(">&%d", fileno $outfile), undef, 'ls')
将根据需要用运行
output.txt
的输出填充您的 ls
。