如何在Perl中锁定文件?

前端之家收集整理的这篇文章主要介绍了如何在Perl中锁定文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Perl中为文件创建锁的最佳方式是什么?

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

解决方法

如果你最终使用flock,这里有一些代码来做:
  1. use Fcntl ':flock'; # Import LOCK_* constants
  2.  
  3. # We will use this file path in error messages and function calls.
  4. # Don't type it out more than once in your code. Use a variable.
  5. my $file = '/path/to/some/file';
  6.  
  7. # Open the file for appending. Note the file path is quoted
  8. # in the error message. This helps debug situations where you
  9. # have a stray space at the start or end of the path.
  10. open(my $fh,'>>',$file) or die "Could not open '$file' - $!";
  11.  
  12. # Get exclusive lock (will block until it does)
  13. flock($fh,LOCK_EX) or die "Could not lock '$file' - $!";
  14.  
  15. # Do something with the file here...
  16.  
  17. # Do NOT use flock() to unlock the file if you wrote to the
  18. # file in the "do something" section above. This could create
  19. # a race condition. The close() call below will unlock the
  20. # file for you,but only after writing any buffered data.
  21.  
  22. # In a world of buffered i/o,some or all of your data may not
  23. # be written until close() completes. Always,always,ALWAYS
  24. # check the return value of close() if you wrote to the file!
  25. close($fh) or die "Could not write '$file' - $!";

一些有用的链接

> PerlMonks file locking tutorial(有点老)
> flock() documentation

为了回应您的补充问题,我会说,将文件锁定在文件上,或者在文件被锁定时创建一个你称之为“锁定”的文件,当它不再被锁定时将其删除(然后确保你的程序服从那些语义)。

猜你在找的Perl相关文章