NAME

flock - lock an entire file with an advisory lock


SYNOPSIS

flock FILEHANDLE,OPERATION


DESCRIPTION

Calls flock, or an emulation of it, on FILEHANDLE. Returns TRUE for success, FALSE on failure. Will produce a fatal error if used on a machine that doesn't implement flock, fcntl locking, or lockf. flock is Perl's portable file locking interface, although it will lock only entire files, not records.

OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but you can use the symbolic names if you pull them in with an explicit request to the Fcntl module. The names can be requested as a group with the :flock tag (or they can be requested individually, of course). LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is added to LOCK_SH or LOCK_EX then flock will return immediately rather than blocking waiting for the lock (check the return status to see if you got it).

Note that the emulation built with lockf doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that lockf implements. Most (all?) systems implement lockf in terms of fcntl locking, though, so the differing semantics shouldn't bite too many people.

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. If you like you can force Perl to ignore your system's flock function, and so provide its own fcntl-based emulation, by passing the switch -Ud_flock to the Configure program when you configure perl.

Here's a mailbox appender for BSD systems.

    use Fcntl ':flock'; # import LOCK_* constants

    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 the DB_File manpage for other flock examples.