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.
| [reply] |
To lock an open filehandle:
flock FH, 2;
To unlock the file:
close FH;
You don't need to explicitly unlock the file. Just close it.
How can I lock a file? | [reply] [d/l] [select] |