我能想到的唯一方法是分離一個通過管道發送回所有東西的子進程(認爲IO :: Pipe或類似IPC :: Open2的東西 - 無論哪種方式,您仍然會將您的STDERR重定向到子代中的STDOUT ),然後在父文件中,將您在管道中獲得的內容寫入日誌文件 - 這可讓您在第一次有數據時打開日誌文件。例如:
#!/usr/bin/perl
use Proc::Fork;
use IO::Pipe;
sub pipe_to_logfile
{
my $log = shift;
my @cmd = @_;
my $pipe = IO::Pipe->new();
run_fork {
child {
$pipe->writer();
open STDOUT, '>&', $pipe or die "Can't redirect STDOUT: $!";
open STDERR, '>&STDOUT' or die "Can't redirect STDERR: $!";
exec(@cmd);
}
parent {
$pipe->reader();
my $fh;
while(<$pipe>)
{
unless ($fh)
{
open $fh, '>', $log or die "Can't write to $log: $!";
}
print $fh $_;
}
}
}
}
pipe_to_logfile('/tmp/true.out', 'true');
pipe_to_logfile('/tmp/ls.out', qw(ls /));
當我跑,我得到:
$ ls /tmp/*.out
ls: cannot access /tmp/*.out: No such file or directory
$ cd tmp
$ perl foo.pl
$ ls /tmp/*.out
/tmp/ls.out
希望有所幫助。
以編程方式檢查和刪除文件。兩條線是困難? – ikegami 2011-04-19 04:08:27