Linux File Locking

Linux supports all fashions of file locking: advisory and mandatory locks, as well as the fcntl( ), flock( ), and the lockf( ) system calls. However, the lockf( ) system call is just a library wrapper routine, and therefore is not discussed here.

fcntl( )'s mandatory locks can be enabled and disabled on a per-filesystem basis using the ms_mandlock flag (the mand option) of the mount( ) system call. The default is to switch off mandatory locking. In this case, fcntl( ) creates advisory locks. When the flag is set, fcntl( ) produces mandatory locks if the file has the set-group bit on and the group-execute bit off; it produces advisory locks otherwise.

In earlier Linux versions, the flock( ) system call produced only advisory locks, without regard of the ms_mandlock mount flag. This is the expected behavior of the system call in any Unix-like operating system. In Linux 2.4, however, a special kind of flock( )'s mandatory lock has been added to allow proper support for some proprietary network filesystem implementations. It is the so-called share-mode mandatory look; when set, no other process may open a file that would conflict with the access mode of the lock. Use of this feature for native Unix applications is discouraged, because the resulting source code will be nonportable.

Another kind of flock( ) -based mandatory lock called leases has been introduced in Linux

2.4. When a process tries to open a file protected by a lease, it is blocked as usual. However, the process that owns the lock receives a signal. Once informed, it should first update the file so that its content is consistent, and then release the lock. If the owner does not do this in a well-defined time interval (tunable by writing a number of seconds into /proc/sys/fs/lease-break-time, usually 45 seconds), the lease is automatically removed by the kernel and the blocked process is allowed to continue.

Beside the checks in the read( ) and write( ) system calls, the kernel takes into consideration the existence of mandatory locks when servicing all system calls that could modify the contents of a file. For instance, an open( ) system call with the o_trunc flag set fails if any mandatory lock exists for the file.

A lock produced by fcntl( ) is of type fl_posix, while a lock produced by flock( ) is of type fl_flock, fl_mand (for share-mode locks), or fl_lease (for leases). The types of locks produced by fcntl( ) may safely coexist with those produced by flock( ), but neither one has any effect on the other. Therefore, a file locked through fcntl( ) does not appear locked to flock( ), and vice versa.

The following section describes the main data structure used by the kernel to handle file locks. The next two sections examine the differences between the two most common lock types: fl_posix and fl_flock.

Continue reading here: File Locking Data Structures

Was this article helpful?

0 0