Programming Perl

Programming PerlSearch this book
Previous: 3.2.38 filenoChapter 3
Functions
Next: 3.2.40 fork
 

3.2.39 flock

flock FILEHANDLE, OPERATION

This function calls flock(2) on FILEHANDLE. See the manual page for flock(2) for the definition of OPERATION. Invoking flock will produce a fatal error if used on a machine that doesn't implement flock(2) or emulate it through some other locking mechanism. Here's a mailbox appender for some BSD-based 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();

Note that flock is unlikely to work on a file being accessed through a network file system.


Previous: 3.2.38 filenoProgramming PerlNext: 3.2.40 fork
3.2.38 filenoBook Index3.2.40 fork