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

have tried below but get this error under windows...

Can't locate object method "fd" via package "SDBM_File" (perhaps you forgot to load "SDBM_File"?) at F:\p\test.pl line 8.

Also can not use MLDM::Sync as the program will be put on different servers

You can see the SDBM_FILE is loaded??

any ideas????

use Fcntl qw(:DEFAULT :flock);
use SDBM_File;
use strict;
my $db = tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666)
or die "Couldn't tie SDBM file 'filename': $!; aborting";
flock($db->fd, LOCK_EX);
#...
undef $db;
untie %h;


I have to use sdbm as I have to create a perl database app that works every where perl is. As the database will allow for multiple uses to view and add data. What is the best way to lock the SDBM_File a small demo would be appreciated. Many thanks Brett Wraight

Replies are listed 'Best First'.
Re: Locking a SDBM_File
by perrin (Chancellor) on Mar 05, 2004 at 04:58 UTC
Re: Locking a SDBM_File
by esskar (Deacon) on Mar 05, 2004 at 03:37 UTC
    use Fcntl qw(:DEFAULT :flock); use SDBM_File; use strict; my $db = tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666) or die "Couldn't tie SDBM file 'filename': $!; aborting"; flock($db->fd, LOCK_EX); #... undef $db; untie %h;
      I once thought that was the correct way to lock an SDBM file, until someone pointed out that there's a timing window
      my $db = tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666) or die "Couldn't tie SDBM file 'filename': $!; aborting"; --> # right here flock($db->fd, LOCK_EX);
      At first, you'd think this wasn't a hole. But opening an SDBM file (the last time I looked) actually causes some file I/O. So what happens in this window is that two processes have read some bookkeeping data from the file into memory, one process gets the lock and proceeds to do things that side effect bookkeeping, while the other process blocks. When the first process frees the lock, the second process unblocks, but has data in memory that is now inconsistent with what's on disk. Oops.

      The way around this is to use a separate file for locking, and acquire the lock before opening the SDBM file.

      I may be working off of stale info, though. Can someone who has access to SDBM source confirm that significant I/O happens when the file gets opened?

      this code works on DB_FILE but not on SDBM_FILE
Re: Locking a SDBM_File
by locked_user erichansen1836 (Sexton) on Mar 20, 2019 at 17:13 UTC
    You're not supposed to place a lock on a data resource directly. Use a semaphore file instead.