[Chapter 3] 3.2.39 flock
Author: Larry Wall, Tom Christiansen & Randal L. Schwartz
Date: 1999-07-02T01:49:20Z

#

| Chapter 3 Functions |

### 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.

3.2.38 fileno |  | 3.2.40 fork