如何在 Perl 中锁定文件? [英] How do I lock a file in Perl?

查看:28
本文介绍了如何在 Perl 中锁定文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中为文件创建锁的最佳方法是什么?

What is the best way to create a lock on a file in Perl?

最好是聚集在文件上还是创建一个锁定文件来放置锁定并检查锁定文件上的锁定?

Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?

推荐答案

如果你最终使用了 flock,这里有一些代码可以做到:

If you end up using flock, here's some code to do it:

use Fcntl ':flock'; # Import LOCK_* constants

# We will use this file path in error messages and function calls.
# Don't type it out more than once in your code.  Use a variable.
my $file = '/path/to/some/file';

# Open the file for appending.  Note the file path is quoted
# in the error message.  This helps debug situations where you
# have a stray space at the start or end of the path.
open(my $fh, '>>', $file) or die "Could not open '$file' - $!";

# Get exclusive lock (will block until it does)
flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";

# Do something with the file here...

# Do NOT use flock() to unlock the file if you wrote to the
# file in the "do something" section above.  This could create
# a race condition.  The close() call below will unlock the
# file for you, but only after writing any buffered data.

# In a world of buffered i/o, some or all of your data may not 
# be written until close() completes.  Always, always, ALWAYS 
# check the return value of close() if you wrote to the file!
close($fh) or die "Could not write '$file' - $!";

一些有用的链接:

针对您添加的问题,我想说要么将锁定放在文件上,要么在文件被锁定时创建一个称为锁定"的文件,并在不再锁定时将其删除(然后确保你的程序遵循这些语义).

In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics).

这篇关于如何在 Perl 中锁定文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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