file locking
Hi. I am writing some scripts for a very active website and am having trouble finding details about how flock() works and how it should be used.
I recall reading something a year or so ago stating a file must be locked every time it is opened, otherwise other flocks will be ignored. I don't remember the details of this article and can't find any other information supporting this.
What i'd like to know is do I need to flock every file every time i open it regardless of whether its being read, written to or appended?
I also ran across this bit of code in UBB which uses a different method to lock files, im assuming to be compatible with windows machines:
sub Lock
{ local ($lockname) = @_;
local ($endtime);
$endtime = 15;
$endtime = time + $endtime;
while (-e $lockname && time < $endtime)
{ open (LOCKFILE, ">$lockname");
} #end lock sr
sub Unlock
{ local ($lockname) = @_;
close (LOCKFILE);
unlink ($lockname);
}
} # end Unlock sr
#usage
&Lock('lock.file');
open (SOMEOTHERFILE, ">$path_to_someotherfile") or die("Unable to open $path_to_someotherfile");
print SOMEOTHERFILE $someotherdata;
close (SOMEOTHERFILE);
&Unlock('lock.file');
A couple of things confuse me about this. First is declaring a sub-routine inside a sub-routine. I didn't know you could, and i dont see the point other than to group the 2 subs.
Second is how it actually works (if it works). It seems to me the while loop in Lock would never execute (because -e $lockname would always be false, if lock.file ever existed it would have been deleted by a previous Unlock).I also question the efficency of continually opening a file for up to 15 seconds.
Any input would be appreciated, i would like to write code that would work on windows machines, but i dont know if i like the UBB alternative.
Vorm posted this at 04:36 — 12th December 2000.
They have: 62 posts
Joined: May 2000
open(HEH, $file);
flock(HEH, 2);
print HEH $_[2];
flock(HEH, 8);
close(HEH);
I think that works. I'm pretty sure you only have to flock when printing to a file, but not when opening one up.
ROB posted this at 09:11 — 16th February 2001.
They have: 447 posts
Joined: Oct 1999
top
k, i ran across this bit of data:
that partially answers some of my questions, correct me if im wrong. a file that has potential to be accessed from other processes should ALWAYS be flocked, and the file pointer needs to be set to 0 using seek but only if the file was being read from, not written to. correct?
also someone suggested to me that file locking is not a concern on windows machines as the operating system does this for you. any truth to that?
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.