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

Can't get flock() to work. Please help...

by alain_desilets (Beadle)
on Aug 30, 2011 at 15:21 UTC ( #923250=perlquestion: print w/replies, xml ) Need Help??
alain_desilets has asked for the wisdom of the Perl Monks concerning the following question:

I have read the excellent tutorial:

But somehow I can't get it to work. For example, here is a little script that (a) opens a file, (b) puts an exclusive lock on it, (c) closes the file (hence in theory releasing the lock), then (d) reopens the file and finally (e) tries to put another exclusive lock on it.

use strict; my $fpath = 'blah.dat'; open(FILEHANDLE_1, ">", $fpath); print "Opened file '$fpath' into FILEHANDLE_1.\n"; flock(FILEHANDLE_1, 2); print "Put exclusive lock on FILEHANDLE_1\n"; close(FILE_HANDLE_1); print "Closed FILEHANDLE_1. It should now be possible to put an exclus +ive lock on file '$fpath'\n"; open(FILEHANDLE_2, ">", $fpath); print "Opened file '$fpath' into FILEHANDLE_2.\n". "Will now try to put an exclusive lock on it.\n"; flock(FILEHANDLE_2, 2); print "Successfully put exclusive lock on FILEHANDLE_2\n";

The problem is that the last line is never printed at all! In other words, the script is not able to secure the second lock, eventhough the first lock should have been released by the closing of FILEHANDLE_1.

What am I doing wrong? Note that I am running this on Windows 7. Could this be a problem with that OS? Does this script run fine on Linux? Thx. Alain Désilets

Replies are listed 'Best First'.
Re: Can't get flock() to work. Please help...
by toolic (Bishop) on Aug 30, 2011 at 15:41 UTC
      Cool! I have been using strict for years, but had never heard of warnings. I'll add that to my standard boilerplate code for Perl scripts. -- Alain

        Then change you file open boilerplate to:

        open my $fileIn, '<', $filename or die "Can't open $filename: $!";

        which uses the three argument form of open (you werre already actually, but just making it explicit), uses lexical file handles (with strict that would have caught your typo too) and reports open errors.

        True laziness is hard work
Re: Can't get flock() to work. Please help...
by DanielSpaniel (Scribe) on Aug 30, 2011 at 15:30 UTC
    You have your close "FILE_HANDLE_1" spelled incorrectly. It should be "FILEHANDLE_1".
      God I feel silly! Sorry about that.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://923250]
Approved by blue_cowdawg
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2018-06-20 23:43 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (117 votes). Check out past polls.