我能想到的唯一方法是分离一个通过管道发送回所有东西的子进程(认为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