flock implements advisory locking. Advisory locking does not prevent anyone from opening a file, reading from it or writting to it. Advisory locking will only prevent others from getting a lock.
To read:
{
# Make sure file gets closed and unlocked when we're done.
local *IN;
open(IN, '<', ...)
or die("...: $!\n");
# Wait for people to stop writting:
flock(IN, LOCK_SH)
or die("...: $!\n");
...
}
To write:
{
# Make sure file gets closed and unlocked when we're done.
local *OUT;
open(OUT, '>>', ...)
or die("...: $!\n");
# Wait for people to stop reading and writting:
flock(OUT, LOCK_EX)
or die("...: $!\n");
# We need to seek if we wish to append,
# in case people have written to the file
# before we obtained the lock.
seek(OUT, SEEK_END, 0)
or die("...: $!\n");
...
}
|