【发布时间】:2014-09-15 06:18:36
【问题描述】:
我需要从 Perl 脚本中调用一个外部日志记录进程,该脚本获取传递给它的数据并将其写入网络服务。这很容易做到。但是,我还有一个额外的要求,即从 parent 进程对 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)上。
关于如何做到这一点的任何建议?
【问题讨论】:
标签: perl