Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

RE: File Locking

by KM (Priest)
on May 22, 2000 at 07:17 UTC ( #14139=note: print w/ replies, xml ) Need Help??


in reply to File Locking

woops, went beyond what I could, I will put this in a few replies... change of having corrupt data.

One good strategy is to move the locking away from the data file altogether by using a semaphore file. Consider the following:

use strict;
use Fcntl qw(:flock);

my $file = 'data.file';
my $SEMAPHORE = "$file.lck";

open(S, ">$SEMAPHORE) || die "Foo ($!)";
flock(S, LOCK_EX);
open(FH, "+<$file") || die "Foofoo ($!)";
# Muck with file
close FH;
close S;

This solves a few problems. First, this allows you to ensure you get a lock when you open a file only for reading. Some systems will not give an exclusive lock on files (which is why you open the semaphore file for write) which were opened only for write only. This gets around that issue. And, by removing the issue of locking completely off the actual data file, you can use one semaphore file to lock multiple files, or directories. And, by removing the locking from the data file you reduce the risk of saying one morning "My hit counter reset itself!".


Comment on RE: File Locking

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://14139]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2014-09-30 20:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (383 votes), past polls