Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

RE: File Locking

by KM (Priest)
on May 22, 2000 at 07:17 UTC ( [id://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!".

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-18 19:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found