File :: Tee的线程安全替代方法? [英] Thread-safe alternative to File::Tee?

查看:92
本文介绍了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;
}

这篇关于File :: Tee的线程安全替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆