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

Hello. I have a DBM file which contains all the members online.
use fcntl qw(:DEFAULT :flock); use DB_File; $lck = $path/whosonline . ".lockfile"; sysopen(DBLOCK, $LCK, O_RDONLY | O_CREAT) or die "can't open $lck: $!" +; flock(DBLOCK, LOCK_SH) or die "cant lock_sh $lck: $1"; dbmopen %who, "$path/whosonline", 0666 or die "Can't open FILENAME: $ +!\n";# open database, accessed through %mname tie %who, "DB_File", "$path/whosonline" or die "Can't open FILENAME: $ +!\n"; # open database tie hash to db $V = $who{$points}; # retrieve from database this is th +e key $who{$Account::cata_acc} = "$time"; # put value into da +tabase this is the value if (exists $who{"$Account::cata_acc"}) { # check whether in data +base } untie %who ; dbmclose %who; # close the database close DBLOCK; #done checking whosonline
Should I lock the file like this? and is it the right way?

Edit: 2001-03-03 by neshura

Replies are listed 'Best First'.
Re: Should I lock this DBM File?
by dws (Chancellor) on Feb 12, 2001 at 09:36 UTC
    Indeed, dbmopen() et al. are remnants of antiquity.

    As to the question, "should I lock", the answer is Yes, with the caveat that you're only protected against other scripts that play by the same rules.

    One hint: If at first you don't get the lock, don't just die. Instead, retry a few times after a short sleep() or select() induced delay. Your script doesn't hold the lock for long, so if a different instance of the script beats you to the lock, chances are good that you'll get it after a short wait.

Re (tilly) 1: Should I lock this DBM File?
by tilly (Archbishop) on Feb 12, 2001 at 09:29 UTC
    tie has superceded dbmopen. The latter is kept only for backwards compatibility with Perl 4 scripts and should not be used.
Re: Should I lock this DBM File?
by merlyn (Sage) on Feb 12, 2001 at 19:33 UTC
    I'm not sure what you're gaining at all by having everyone use a LOCK_SH. If you change LOCK_SH to LOCK_EX, I think we have room for discussion.

    "I'll have what she's having". That's all you've said, and the answer is always yes.

    -- Randal L. Schwartz, Perl hacker