[英]Write Perl's system call output to a file
我正在嘗試合並Perl腳本的STDOUT和STDERR流,並將其派生到日志文件中。
open( MERGED, "|-", "tee /tmp/my.log" );
*STDOUT = *MERGED;
*STDERR = *MERGED;
print "1: print\n";
warn "2: warn\n";
system "echo 3: system call";
在此示例中,“打印”和“警告”消息同時出現在終端和日志中,而系統調用僅出現在終端中。
如何將輸出流拆分到日志文件?
注意:僅需要在Unix上工作,我不想依賴不屬於標准Perl發行版的軟件包(例如File :: Tee,IO :: Tee ..)。
子程序對Perl的變量一無所知。 如果要重定向孩子的標准輸出,則需要重定向文件描述符1。
open(my $MERGED, "|-", "tee", "/tmp/my.log") or die $!;
open(STDOUT, '>&', $MERGED) or die $!;
open(STDERR, '>&', $MERGED) or die $!;
僅供參考:這是我根據池上的建議提出的:
$| = 1;
# Hold on to the original handles
open(my $STDOUT_ORIG, '>&', \*STDOUT) or die $!;
open(my $STDERR_ORIG, '>&', \*STDERR) or die $!;
# Fork to log
open( my $ONE, "|-", "tee /tmp/my0.log" ) || die $!;
open( STDOUT, '>&', $ONE ) || die $!;
open( STDERR, '>&', $ONE ) || die $!;
# Make some noise
print "1: print\n";
warn "2: warn\n";
system "echo 3: system call";
# Unhook from the first `tee`
open( STDOUT, '>&', $STDOUT_ORIG ) || die $!;
open( STDERR, '>&', $STDERR_ORIG ) || die $!;
close($ONE);
# Fork to next log
open( my $TWO, "|-", "tee /tmp/my1.log" ) || die $!;
open( STDOUT, '>&', $TWO ) || die $!;
open( STDERR, '>&', $TWO ) || die $!;
print "A: print\n";
warn "B: warn\n";
system "echo C: system call";
close(STDERR);
close(STDOUT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.