Unix-esque partial-file-locking mechanism

Linux and AFAIK most unixes expose the flock syscall for mandatory file-locking. My experience is admittedly limited with this, however am informed that it is kernel-enforced on the entire resource. But what if I wanted to only lock a part of a file mandatorily, such that read/writes to this resource are permitted, as long as they don’t cross a particular boundary or stop reading once it reaches an outer bound of the locked region. Is this possible?

Edit: Possible Implementation

A possibility for advisory partial locking may be via MMaped regions, where the memory is mapped into each reader’s address-space, on the condition that the requested region does not hold a lock. This would be implemented entirely in user-space, and thus loses the advantages of kernel-enforced locking, but would certainly work

Asked By: J-Cake


You can acquire partial lock using the the fcntl(2) system call by the F_SETLK, F_SETLKW, or F_GETLK command macros, and providing the partial area to be locked through a an flock structure provided as the third argument.

F_SETLK, F_SETLKW, and F_GETLK are used to acquire, release, and test
for the existence of record locks (also known as byte-range,
file-segment, or file-region locks). The third argument, lock, is a
pointer to a structure that has at least the following fields (in
unspecified order).

struct flock {
    short l_type;    /* Type of lock: F_RDLCK,
                        F_WRLCK, F_UNLCK */
    short l_whence;  /* How to interpret l_start:
                        SEEK_SET, SEEK_CUR, SEEK_END */
    off_t l_start;   /* Starting offset for lock */
    off_t l_len;     /* Number of bytes to lock */
    pid_t l_pid;     /* PID of process blocking our lock
                        (set by F_GETLK and F_OFD_GETLK) */

The l_whence, l_start, and l_len fields of this structure specify the
range of bytes we wish to lock.
Bytes past the end of the file may be
locked, but not bytes before the start of the file.

Answered By: aviro
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.