Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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!".

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://14139]
NodeReaper lights some incense and reads Tool and Die

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2018-07-21 17:57 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (449 votes). Check out past polls.