Gossamer Forum
Home : General : Perl Programming :

Flocking Files

Quote Reply
Flocking Files
It seems on some servers that file locking using the flock command generates errors. I'm not sure if this is caused by the handle number used. I use 2 which is usually supplied in the literature - for example:

flock (DAT, 2);

Is there some servers (like NT servers etc.)that require a different handle? Also, is it recommended to unlock the file when done before closing the file? For example:

unlock (DAT, 8);

Dan Smile
Quote Reply
Re: Flocking Files In reply to
You can get the proper magic numbers out of Fcntl I believe, not sure the exact syntax. I've never seent them as anything but 1,2,4 and 8.

As for unlocking, you always want to let perl handle the unlock automatically with close() unless you know what you are doing.

Cheers,

Alex
Quote Reply
Re: Flocking Files In reply to
Thanks (for the helpful reply to this question and other one regarding associative arrays). Here is what I found doing a quick Yahoo web search on fnctl+perl:

open(IN, $file);
fcntl(IN, 7, 0); # Lock
.
.
.
fcntl(IN, 3, 0); # Unlock
close(IN);

I take it that fcntl locates a valid handle to lock and unlock files. Do you know if in this case it is necessary to explicitly unlock the file?

Also, have you encountered a server that errors when using flock(IN, 2)? Works on all the servers that I have used but for a couple of people using my mods, this file locking (at least when handle = 2) does not work. This is why I'd like to make the mods more compatible.

Dan Smile
Quote Reply
Re: Flocking Files In reply to
Hi,
can you tell me where docs about this function are on the Internet (URL). What is the number? Is that a timeout?

Quote Reply
Re: Flocking Files In reply to
From the docs:

You can request that the flock() constants (LOCK_SH, LOCK_EX, LOCK_NB and LOCK_UN) be provided by using the tag `:flock'. See the Exporter manpage.

So...

#!/usr/bin/perl -w

use Fcntl qw/:flock/;

open(MYFILE, '>blah.txt') or die $!;
flock(MYFILE, LOCK_EX) or die $!;
# Do stuff
close(MYFILE) or die $!;

--mark

Installation support is provided via ICQ at UIN# 53788453. I will only respond on that number.
Quote Reply
Re: Flocking Files In reply to
Just to complete this post :)

----
use Fcntl qw/:flock/;


open(FILE, ">>/path/to/file")
flock(FILE,LOCK_EX);
#if someone try to use the file
seek(FILE,0,2);
#your action here
flock(FILE,LOCK_UN);
close(FILE);
--------

I hope this helps.



Quote Reply
Re: Flocking Files In reply to
Actually unless you are doing something special, you almost never want flock(FH, LOCK_UN). Perl's close will unlock the file automatically and ensure that the buffer has been properly written to disk.

Cheers,

Alex

--
Gossamer Threads Inc.