File :: Tee的线程安全替代方法?
I was wanting to implement some logging for a threaded script I have, and I came across File::Tee. However, when attempting to ppm
the module on a Windows box, it's not found (and according to activestate, not supported on Windows).
我真的很喜欢您可以通过执行以下操作来锁定文件访问:
I really liked that you could lock file access though, by doing something like:
tee STDOUT, {mode => '>>', open => '$ENV{DOM}\\threaded_build.log', lock => 1};
tee STDERR, {mode => '>>', open => '$ENV{DOM}\\threaded_debug.log', lock => 1};
是否存在跨平台,线程安全的替代方案?
Is there a cross-platform, thread-safe alternative?
File::Tee
格外小心,以处理通过system
或未通过perlio的XS代码运行的外部程序生成的输出.我认为这就是它与Windows不兼容的原因.
File::Tee
takes extra care to handle output generated by external programs run through system
or XS code that doesn't go through perlio. I think that's what makes it incompatible with Windows.
IO::Tee
更具跨平台性,我认为使其变得线程安全不会太难. File::Tee
中的同步代码就像:
IO::Tee
is more cross-platform and I don't think making it thread safe would be too hard to do. The sync code in File::Tee
just looks like:
flock($teefh, LOCK_EX) if $target->{lock};
print $teefh $cp;
flock($teefh, LOCK_UN) if $target->{lock};
您可以通过修改以下两种方法在IO::Tee
中完成相同的操作:
You could accomplish the same thing in IO::Tee
by modifying a couple of methods:
use Fcntl ':flock';
no warnings 'redefine';
sub IO::Tee::PRINT
{
my $self = shift;
my $ret = 1;
foreach my $fh (@$self) {
flock($fh, LOCK_EX);
undef $ret unless print $fh @_;
flock($fh, LOCK_UN);
}
return $ret;
}
sub IO::Tee::PRINTF
{
my $self = shift;
my $fmt = shift;
my $ret = 1;
foreach my $fh (@$self) {
flock($fh, LOCK_EX);
undef $ret unless printf $fh $fmt, @_;
flock($fh, LOCK_UN);
}
return $ret;
}