in reply to Re: Re: File locking, lock files, and how it all sucks
in thread File locking, lock files, and how it all sucks
then you have a race condition that can cause file corruption.open(FILE, ">>$path") or die "$! writing $path"; &lock; # calls flock(FLOCK_EX) and logs print FILE $string; &unlock; # calls flock(FLOCK_UN) and logs close FILE;
Consider what happens if the open succeeds and the flock blocks to obtain the lock. The open has positioned you for writing to the end of the file. But if the process that holds the lock writes after you've opened the file, the end-of-file mark moves. You're now positioned to overwrite whatever the other process wrote. If your string is longer, their string gets lost. If your string is shorter, you probably corrupt the file.
The way around this is to seek to end-of-file after you've obtained the lock.
open(FILE, ">>$path") or die "$! writing $path"; &lock; seek(FILE, 0, 2); # ensure positioned at EOF print FILE $string; ...
|
|---|