How do I lock a file in Perl?

前端 未结 14 586
礼貌的吻别
礼貌的吻别 2020-12-01 05:45

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

14条回答
  •  时光取名叫无心
    2020-12-01 06:16

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

    Some useful links:

    • PerlMonks file locking tutorial (somewhat old)
    • flock() documentation

    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).

提交回复
热议问题