2014-07-23 58 views
4

我需要從一個Perl腳本調用一個外部日誌記錄進程,該腳本將數據傳遞給它並寫入網絡服務。這很容易做到。但是,我有額外的要求,即從父級進程向STDERR的任何寫入都會被重定向到外部進程。將父進程的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)上。

有關我如何做到這一點的任何建議?

回答

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; 
相關問題