flock

NAME

flock - lock an entire file with an advisory lock


SYNOPSIS

flock FILEHANDLE,OPERATION


DESCRIPTION

Calls flock(2) on FILEHANDLE. See flock(2) for definition of OPERATION. Returns TRUE for success, FALSE on failure. Will produce a fatal error if used on a machine that doesn't implement either flock(2) or fcntl(2). The fcntl(2) system call will be automatically used if flock(2) is missing from your system. This makes flock() the portable file locking strategy, although it will only lock entire files, not records. Note also that some versions of flock() cannot lock things over the network; you would need to use the more system-specific fcntl() for that.

Here's a mailbox appender for BSD systems.

$LOCK_SH = 1; $LOCK_EX = 2; $LOCK_NB = 4; $LOCK_UN = 8; sub lock { flock(MBOX,$LOCK_EX); # and, in case someone appended # while we were waiting... seek(MBOX, 0, 2); } sub unlock { flock(MBOX,$LOCK_UN); }
    open(MBOX, ``>>/usr/spool/mail/$ENV{'USER'}'')
            or die ``Can't open mailbox: $!'';
    lock();
    print MBOX $msg,"\n\n";
    unlock();

See also DB_File for other flock() examples.