我正在尝试将分叉进程的STDOUT
分配给管道。例如为分叉进程重新分配STDOUT
use warnings;
use strict;
use feature qw(say);
use IO::Select;
my $cmd='sleep 2; echo Hello';
pipe(PREAD, PWRITE);
my $pid=fork();
if ($pid==0) {
*STDOUT=*PWRITE;
exec $cmd;
die "Could not run command \"$cmd\"";
}
my $sel = IO::Select->new(\*PREAD);
say "Waiting for background process..";
while (1) {
my @ready = $sel->can_read;
last if (! @ready);
for my $fh (@ready) {
say "Processing file descriptor ".($fh->fileno());
my $line=<$fh>;
if (! defined $line) {
say "EOF";
$sel->remove($fh);
next;
}
chomp($line);
say "Got line: \"$line\"..";
}
}
waitpid ($pid,0);
say "Done.";
但是没有任何内容出现在管道中PREAD
;孩子仍然输出到STDOUT
而不是管道。
perl有一个快捷方式:'打开我的$ pipe,'$ cmd |''或'打开我的$ pipe,' - ',$ cmd,@ args'。请参阅[文档](https://metacpan.org/pod/distribution/perl/pod/perlfunc.pod#open-FILEHANDLE-EXPR)。 – salva 2014-09-01 07:01:04