Locking Strategies

The issues of safe access to databases that plagued flat-file databases still apply to Berkeley databases. Therefore, it is a good idea to implement a locking strategy that allows safe multi-user access to the databases, if this is required by your applications.

The way in which flock() is used regarding DBM files is slightly different than that of locking standard Perl filehandles, as there is no direct reference to the underlying filehandle when we create a DBM file within a Perl script.

Fortunately, the DB_File module defines a method that can be used to locate the underlying file descriptor for a DBM file, allowing us to use flock() on it. This can be achieved by invoking the fd() method on the object reference returned from the database initialization by tie(). For example:

### Create the new database ...
$db = tie %database, 'DB_File', "megaliths.dat"
    or die "Can't initialize database: $!\n";

### Acquire the file descriptor for the DBM file
my $fd = $db->fd();

### Do a careful open() of that descriptor to get a Perl filehandle
open DATAFILE, "+<&=$fd" or die "Can't safely open file: $!\n";

### And lock it before we start loading data ...
print "Acquiring an exclusive lock...";
flock( DATAFILE, LOCK_EX )
        or die "Unable to acquire exclusive lock: $!. Aborting";
print "Acquired lock. Ready to update database!\n\n";

This code looks a bit gruesome, especially with the additional call to open(). It is written in such a way that the original file descriptor being ...

Get Programming the Perl DBI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.