gpt4 book ai didi

perl - 如何在 Perl 中锁定文件?

转载 作者:行者123 更新时间:2023-12-03 09:40:45 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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' - $!";

一些有用的链接:
  • PerlMonks file locking tutorial (有点旧)
  • flock() documentation

  • 为了回答您添加的问题,我想说要么将锁定放在文件上,要么在文件被锁定时创建一个称为“锁定”的文件,并在不再锁定时将其删除(然后确保您的程序遵守那些语义)。

    关于perl - 如何在 Perl 中锁定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com