I couldn't really decide where to put this, but I figured Meditations would be best.
I was working with a script yesterday and realized that flock() doesn't do much by itself.
Using a simple flock FILEHANDLE, LOCK_EX; won't always succeed in locking a file.
So, I created a subroutine that attempts to lock a file several times, and if it cannot, there is definitely something wrong, and the user is presented with an error.
I surprised myself by using pop()!
Anyway, this code is very easy to use:
lockfile (FILEHANDLE);
I was working with a script yesterday and realized that flock() doesn't do much by itself.
Using a simple flock FILEHANDLE, LOCK_EX; won't always succeed in locking a file.
So, I created a subroutine that attempts to lock a file several times, and if it cannot, there is definitely something wrong, and the user is presented with an error.
So here is the small subroutine:
There. Very easy subroutine that will try flocking a file 10 times before informing the user of an error.sub lockfile { my $file = pop(); for $i (1 .. 10) { sleep .15; $locked = 1 if (flock $file, LOCK_EX); } unless ($locked == 1) { print "\n\nFlock error: could not lock $file"; + exit; } }
I surprised myself by using pop()!
Anyway, this code is very easy to use:
lockfile (FILEHANDLE);
I could have also allowed an optional parameter that would allow the user to pass what kind of lock to use, rather than simply applying LOCK_EX, but I always use LOCK_EX, so...
Better not be an error in that post... ;-)
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: Flock Subroutine
by tye (Sage) on Jul 28, 2000 at 03:26 UTC | |
by redmist (Deacon) on Jul 29, 2000 at 06:57 UTC | |
RE: Flock Subroutine
by merlyn (Sage) on Jul 28, 2000 at 07:24 UTC | |
RE: Flock Subroutine
by chip (Curate) on Jul 28, 2000 at 15:17 UTC | |
RE: Flock Subroutine
by KM (Priest) on Jul 28, 2000 at 20:56 UTC | |
by turnstep (Parson) on Jul 29, 2000 at 07:47 UTC | |
by KM (Priest) on Aug 07, 2000 at 18:59 UTC | |
by turnstep (Parson) on Aug 08, 2000 at 04:35 UTC | |
by KM (Priest) on Aug 08, 2000 at 17:29 UTC | |
| |
RE: Flock Subroutine
by turnstep (Parson) on Jul 28, 2000 at 20:46 UTC |
Back to
Meditations