我正在嘗試將分叉進程的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