http://qs321.pair.com?node_id=208926

stupidius has asked for the wisdom of the Perl Monks concerning the following question:

Greetings and salutations monks. I am stupidius, of the clan, Stupid. I am sent forth to you today to seek your wisdom in the matter of the flock function. Several scripts on mine website may run simultaneously, and they may requireth access to a certain file for reading and/or writing. What is the proper way to flock a file so that if that certain file is needed, the calling script will wait for it to be released if it is locked? I do not merely wish to lock it and have other scripts return errors, but rather, have each one wait there turn. I thank thee in advance, and my apologies for my poor rendition of Ye Old English. Johnius Stupidius of the Stupid Clan

Replies are listed 'Best First'.
Re: Proper use of flock
by Aristotle (Chancellor) on Oct 30, 2002 at 00:38 UTC
    Start out with use Fcntl qw(:flock); Right after you open a file for reading, do flock FH, LOCK_SH or die "Failed acquiring shared lock on $filename: $!"; If you want to write to a file, do flock FH, LOCK_EX or die "Failed acquiring ex. lock on $filename: $!";

    DO NOT unlock the file, ever. Just close it. If you want to read from a file and then also write to it, then open it for reading and writing once, and get a shared lock. Once you want to write to it, upgrade to an exclusive lock by calling flock on the file handle again - do not close and reopen it. Don't downgrade that lock to a shared one either.

    See perldoc -f flock for help on the function.

    Makeshifts last the longest.

      I agree with everything Aristotle said, I just wanted to point something out that may not be obvious.

      Where it says "If you want to write to a file, do"...

      Make sure you do NOT open the file with a single >, or in truncate mode.

      The lock is, as explained in the docs, only an advisory lock, which means if some code does not check the lock there are no restrictions on it going in and messing with the file.

      So while a good citizen your code locks a file and is doing some reading, a bad citizen could open, truncate, the file if they never check the lock, and your code will be out of luck.

      And not mentioned is locking multiple files, a common mistake is made in the order you lock files. The rule is, all code should lock resources in the same order. And when you release locks you should do in the inverse order. If you have some code that locks A, B, C, and other code that locks C, A you are going to eventually hit deadlock.

      Can you tell I made some mistakes in the past ;-)

      Hope this helps!
      You are a wise and noble monk. Thank you for the info, and thanks for the correction on the other post!!!