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

I need a quick expanation on this whole flock() command! First of all, what parameter do I pass to flock() to simply block write access? Is it flock(2)? And how do I unlock a file so that it can be written to again? I need this because I am designing a user page, where usernames, passwords, and other preferences are stored in a file, and that file is constantly being read from and appended to. One more thing: how do I refer to what filehandle I want to lock? Any help is greatly needed and appreciated!

Replies are listed 'Best First'.
Re: Flock
by turnstep (Parson) on Apr 04, 2000 at 08:22 UTC

    First, take a look at your local man flock docs: I'm assuming you are on a unix system. Here's some quick notes about file locking:

    • Know the difference between shared and exclusive locks, as well as blocking vs. non-blocking.
    • Perl does not necessarily know what LOCK_SH and the others are. Define them in a sub or just use the numeric values.
    • Remember that *all* your processes should honor (and check for) the locks, or all bets are off. This includes any command prompt programs!
    • When in doubt, open the file in read/write mode ("+< $myfile")
    • Reading a file: open read, lock, read, close (also unlocks)
    • Writing a file: open read/write, lock, read, seek (beginning), truncate, rewrite, close
    • Appending a file: open append, lock, seek (end), write, close
    • Use sleep() to test your locks: have one process lock it, then sleep for 30 seconds, while you try to open it with another process. The second should be forced to wait for the first.
    • Avoid lockf. Flock is your friend. :)

    Finally, you say the file is being "constantly read from and appended to." Isn't it also going to be rewritten occasionally as people change their prefs and/or passwords? If you are definitely only appending, then you probably do not need a lock for those who are merely reading the file, as the addition of the appended information is not important on a small time scale.

Re: Flock
by btrott (Parson) on Apr 04, 2000 at 01:58 UTC