Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

flock

Status
Not open for further replies.

Kirsle

Programmer
Joined
Jan 21, 2006
Messages
1,179
Location
US
There's something I never quite understood about file locking with flock:

Code:
use Fcntl qw(:flock);

open (FH, "file.ext"); # open a file here

flock (FH, LOCK_EX); # lock it here

Isn't there theoretically a tiny window of opportunity between when you open the file and when you lock it, to where another process might want to open the file and read/write to it?

I've always just used lockfiles, such as:

Code:
my $i = 0;
while (-f "lockfile.lck") {
   sleep 1;
   $i++;
   die "Can't gain access to the lock" if $i > 30;
}

open (LCK, ">lockfile.lck");
print LCK "it's mine now, suckas!";
close (LCK);

open (FILE, "the_file.txt");
my @data = <FILE>;
close (FILE);

# manipulate

open (FILE, ">the_file.txt");
print FILE join ("\n",@data);
close (FILE);

# unlock
unlink "lockfile.lck";

So does flock have a slight possibility of defeating its own purpose, or is the nanosecond of time between opening and locking too insignificant and statistically unlikely to be intercepted by another process to even worry about it?

-------------
Cuvou.com | The NEW Kirsle.net
 
I haven't used flock but does it fix the problem of locks hanging around if you program dies for some reason?

When I used file locks (as you are doing) I always had a check for the age of the lock and deleted it if it was held longer than $x ($x usually being the max normal time my program should run times 3). That way if a program died unexpectedly it had a chance to recover later.

I really don't have this problem anymore cause everything goes to a DB :)
 
In the hand-rolled code you posted, there's also a gap between when you check for the existence of the file (with -f) and creating it.

In the flock example you posted, yes there is indeed a possible window between "open" and "flock" but it won't have an adverse effect. You've opened the file for reading, then you attempt to get a lock on the file you've opened. There's no threat to data integrity, as you're not changing anything. Once whatever else that may have a lock on the file releases it, you proceed and read from the file.

It's a little different when writing to a file though. Have a look at the "File locking" section of perlopentut for more on this.
 
Status
Not open for further replies.

Similar threads

Replies
4
Views
222
Replies
2
Views
145
  • Locked
  • Question Question
Replies
2
Views
108
Replies
7
Views
324

Part and Inventory Search

Sponsor

Back
Top