1

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

1 Answer 1

0

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .