P is for Practical | |
PerlMonks |
Re: Order of flock and openby ferrency (Deacon) |
on Apr 30, 2003 at 16:50 UTC ( [id://254381]=note: print w/replies, xml ) | Need Help?? |
Other posters are mostly correct: Most of the time, you don't need to worry about the fact that there's a delay between the open() and flock() calls. But there are some cases you should be aware of which require more careful consideration. One issue is if you're opening a file for something other than reading. If you open a file for append, you should seek() to the end of the file after you acquire the lock, to make sure no one else appended to the file after you opened it.
If you're opening a file for destructive write, you have a bigger problem. Opening destroys the file, but you can't lock the file until you open it. One solution to this is to lock a different file, as someone else described. Another solution is to open the file twice: open it once for reading, lock it, and then open it for writing once you know you have the lock. As long as you keep the first filehandle open, you'll keep the lock.
Finally, is the situation you describe, where you want to lock a file, rebuild it in a temporary file, and then copy the tempfile over the real file. The issue here is, with most filesystems, when you use rename() or `mv` to replace the real file with the newly built tempfile, you lose your lock on the file. If this is okay (you're done with the file when you copy it over) then it's probably not a problem. But if you wanted to perform any other operations on the file while it's still locked, you probably need to use the "lock a different file" technique. Alan
In Section
Seekers of Perl Wisdom
|
|