将父进程的STDERR重定向到子进程的文件句柄

时间:2014-07-23 21:13:14

标签: perl

我需要从Perl脚本调用外部日志记录进程,该脚本将传递给它的数据并将其写入网络服务。这很容易做到。但是,我有额外的要求,即从进程对STDERR的任何写入都会被重定向到外部进程。

我尝试过做的是打开外部进程写管道的文件句柄,然后将STDERR重定向到文件句柄。这是我的测试脚本,遗憾的是还没有用。

#!/usr/bin/perl

use strict;
use warnings;

# open write filehandle to external process
open my $fh, '|-', 'pipefile_http',
  or die "Couldn't open logfile: $!\n";

# redirect STDERR from parent process to same write filehandle to child process
my $fileno = fileno($fh);
open STDERR, ">&$fileno" or die "Couldn't switch STDERR to fileno $fileno: $!\n";

print $fh "1. print to file handle\n";

print STDERR "2. print to STDERR\n";

print "3. print to STDOUT\n";

close $fh;

exit 0;

当我运行此脚本时,它成功地将对STDERR的打印调用重定向到外部日志记录过程,但是对$ fh的打印调用不起作用(消息消失)。此外,脚本在成功将消息#3打印到STDOUT后无限期挂起。当我用strace运行脚本时,我可以看到脚本挂在waitpid()调用(外部进程的pid)上。

关于我如何做到这一点的任何建议?

1 个答案:

答案 0 :(得分:3)

重新分配STDERR

#!/usr/bin/perl
use strict;
use warnings;

# open write filehandle to external process
open my $fh, '|-', 'pipefile_http',
    or die "Couldn't open logfile: $!\n";

# reassign STDERR
*STDERR = $fh;

print $fh "1. print to file handle\n";
print STDERR "2. print to STDERR\n";
print "3. print to STDOUT\n";

close $fh;

exit 0;
相关问题