Easy file locking technique 
Author Message
 Easy file locking technique

This is so simple that it now seems obvious, but I don't remember
having seen it before:

        sub get_lock {
          my $lockfile = shift;
          open my $fh, "+< $lockfile"
            or die "Couldn't open lockfile $lockfile: $!; aborting";
          flock $fh, LOCK_EX
            or die "Couldn't lock lockfile $lockfile: $!;  aborting";
          return $fh;
        }

To use this, you do:

        {
          my $lock = get_lock($LOCKFILE);

          # code inside this block is only performed while the file is locked

        }

        # when control exits the block for any reason, the lock is
        # automatically released

A variation has:

        eval {
          my $lock = get_lock($LOCKFILE);

          # code inside this block is only performed while the file is locked
          # when control leaves the block, the lock is automatically released
        };

          # couldn't get lock file...
        }



Sun, 21 Dec 2003 01:05:52 GMT  
 Easy file locking technique
: This is so simple that it now seems obvious, but I don't remember
: having seen it before:
[snip]

Pretty cool.  I've actually often thought it would be cool to add yet
another piece of magic to the mode string on file opens; an appended '?'
to mean 'lock for share', and '!' meaning 'lock exclusively'.  Then you
could just do

  open my $fh, '+<! foo.bar' or die "Can't open and lock: $!";

Seems to be in the spirit of Perl, and it would save a lot of grief.  Note
that the scoping trick is automatic given the use of a lexical for the
filehandle; just enclose it in a bare block if it isn't otherwise scope-
constrained.

--
   |   Craig Berry - http://www.cinenet.net/~cberry/
 --*--  "Magick is the art and science of causing change in conformity
   |   with Will."  - Aleister Crowley



Sun, 21 Dec 2003 07:58:02 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Source C to Pascal

2. Looking for programs writen in BOrland Pascal

3. Easy XCOPY Hack For Win32 File Lock

4. PERLFUNC: flock - lock an entire file with an advisory lock

5. PERLFUNC: flock - lock an entire file with an advisory lock

6. Appropriate technique for altering a text file?

7. File compression technique question

8. File::Find recursive technique?

9. Crystal Reports

10. DOS Comms Program not working under Windows

11. Delphi 1 C/S & MS-SQL database BIG problem !

12. File Locking and File Deletion

 

 
Powered by phpBB® Forum Software