O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Locking DBM Files

Problem

You need several concurrently running programs to have simultaneous access to a DBM file.

Solution

Either use the DBM implementation’s locking mechanism if it has one, lock the file with flock, or use an auxiliary locking scheme as in Section 7.21.

Discussion

With SDBM or NDBM, you can’t do much to lock the database itself. You must devise an auxiliary locking scheme using an extra lockfile.

GDBM uses the concept of readers and writers: either many readers or one solitary writer may have a GDBM file open at any given time. You specify whether you’re a reader or a writer when you open it. This can be annoying.

Version 1 of Berkeley DB gives you access to the file descriptor of the open database, allowing you to flock it. The lock applies to the database as a whole, not to individual records. Version 2 implements its own full transaction system with locking.

Example 14.3 shows an example of locking a database using Berkeley DB. Run this repeatedly in the background to see locks granted in proper order.

Example 14-3. dblockdemo

#!/usr/bin/perl
# dblockdemo - demo locking dbm databases use DB_File; use strict; sub LOCK_SH { 1 } # In case you don't have sub LOCK_EX { 2 } # the standard Fcntl module. You sub LOCK_NB { 4 } # should, but who can tell sub LOCK_UN { 8 } # how those chips fall? my($oldval, $fd, $db, %db, $value, $key); $key = shift || 'default'; $value = shift || 'magic'; $value .= " $$"; $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0666) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required