DimG
DimG

Reputation: 1781

flock() vs. fcntl() semantics in glibc

Related: one, two

It's stated that flock() (BSD-locks) and fcntl() (POSIX record-level locks) gives the user incompatible semantics, particularly, in regards of lock release.

However, in glibc flock() is implemented in terms of POSIX fcntl(). (I checked this on official git repo, here is just a viewable link)

https://code.woboq.org/userspace/glibc/sysdeps/posix/flock.c.html#18

/* This file implements the flock' function in terms of the POSIX.1fcntl' locking mechanism. In 4BSD, these are two incompatible locking mechanisms, perhaps with different semantics? */

How can these facts hold together?

Upvotes: 3

Views: 732

Answers (2)

DimG
DimG

Reputation: 1781

NOTE. This is completely wrong, see the accepted answer. Still keeping it alive since it has a few useful links

Well, this was quite dull -- fcntl uses same flock struct as an argument and differentiates open file locks (BSD locks in my notation above) from process-associated file locks (POSIX record-level locks in my notation above) on a l_pid field value basis.

glibc docs on Open File Description Locks:

Open file description locks use the same struct flock as process-associated locks as an argument (see File Locks) and the macros for the command values are also declared in the header file fcntl.h. To use them, the macro _GNU_SOURCE must be defined prior to including any header file.

...

In contrast to process-associated locks, any struct flock used as an argument to open file description lock commands must have the l_pid value set to 0. Also, when returning information about an open file description lock in a F_GETLK or F_OFD_GETLK request, the l_pid field in struct flock will be set to -1 to indicate that the lock is not associated with a process.

Also, see glibc doc on process-associated file locks

Upvotes: 0

Florian Weimer
Florian Weimer

Reputation: 33717

On Linux, flock is a system call. flock locks and fcntl locks are independent and do not interfere with each other (on local file systems at least).

The glibc source file sysdeps/posix/flock.c is not actually used on Linux. The real implementation is the system call wrapper generated from this line in sysdeps/unix/sysv/linux/syscalls.list:

flock             -       flock           i:ii    __flock         flock

OFD locks are yet another kind of locks, but they do interact with POSIX record locks. However, they have more reasonable behavior with multiple threads, and closing one descriptor does not release all locks for the same underlying file held by the same process (which makes POSIX record locking so difficult to use in multi-threaded processes).

Upvotes: 3

Related Questions