jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

I'm doing a simple experiment: I'm locking a file with the result that my other script will not be able to write or read to/from this file.
Locking the file: flock(IN,LOCK_EX) ;
opening the file: open OUT,">my_locked_file.txt" or die "Cannot open file\n";
So what happened, my script didn't have any problems with opening this file
Any suggestions how I should open files obaying the lock-rules ?

Thanks in advance
Luca

Replies are listed 'Best First'.
Re: flock and open
by ikegami (Patriarch) on Feb 08, 2006 at 16:36 UTC

    flock implements advisory locking. Advisory locking does not prevent anyone from opening a file, reading from it or writting to it. Advisory locking will only prevent others from getting a lock.

    To read:

    { # Make sure file gets closed and unlocked when we're done. local *IN; open(IN, '<', ...) or die("...: $!\n"); # Wait for people to stop writting: flock(IN, LOCK_SH) or die("...: $!\n"); ... }

    To write:

    { # Make sure file gets closed and unlocked when we're done. local *OUT; open(OUT, '>>', ...) or die("...: $!\n"); # Wait for people to stop reading and writting: flock(OUT, LOCK_EX) or die("...: $!\n"); # We need to seek if we wish to append, # in case people have written to the file # before we obtained the lock. seek(OUT, SEEK_END, 0) or die("...: $!\n"); ... }
Re: flock and open
by jeanluca (Deacon) on Feb 08, 2006 at 16:51 UTC
    Thnx, it works ?
    Why: local *OUT ; ?

    Luca

      Why would you want to use a global? Localizing the variable

      • prevents conflicts with an existing OUT file handle (if one exists),
      • makes sure the file handle gets closed as soon as the block/sub exits (whether it exited normally or via die),
      • makes sure the file handle gets flushed as soon as the block/sub exits (whether it exited normally or via die, since file handles are flushed when they are closed), and
      • makes sure the lock is realeased as soon as the block/sub exits (whether it exited normally or via die, since the lock is automatically realeased when the file handle is closed).

      You should always limit the scope of your variables to where they are needed, using local or (even better) my.

        Well, then why not using lexical filehandles? e.g

        { # Make sure file gets closed and unlocked when we're done. open(my $IN, '<', ...) or die("...: $!\n"); # Wait for people to stop writting: flock($IN, LOCK_SH) or die("...: $!\n"); while (my $line = <$IN>) { ... } # close ($IN); # not really needed => closed at end of block }

        Best regards,
        perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"