The Linux Programming Interface

(nextflipdebug5) #1

1138 Chapter 55


Linux, like many other UNIX implementations, also allows fcntl() record locks to be
mandatory. This means that every file I/O operation is checked to see whether it is
compatible with any locks held by other processes on the region of the file on
which I/O is being performed.

Advisory mode locking is sometimes referred to as discretionary locking, while
mandatory locking is sometimes referred to as enforcement-mode locking. SUSv3
doesn’t specify mandatory locking, but it is available (with some variation in
the details) on most modern UNIX implementations.

In order to use mandatory locking on Linux, we must enable it on the file system
containing the files we wish to lock and on each file to be locked. We enable manda-
tory locking on a file system by mounting it with the (Linux-specific) –o mand option:

# mount -o mand /dev/sda10 /testfs

From a program, we can achieve the same result by specifying the MS_MANDLOCK flag
when calling mount(2) (Section 14.8.1).
We can check whether a mounted file system has mandatory locking enabled
by looking at the output of the mount(8) command with no options:

# mount | grep sda10
/dev/sda10 on /testfs type ext3 (rw,mand)

Mandatory locking is enabled on a file by the combination of having the set-group-
ID permission bit turned on and the group-execute permission turned off. This
combination of permission bits was otherwise meaningless and unused in earlier
UNIX implementations. In this way, later UNIX systems added mandatory locking
without needing to change existing programs or add new system calls. From the
shell, we can enable mandatory locking on a file as follows:

$ chmod g+s,g-x /testfs/file

From a program, we can enable mandatory locking for a file by setting permissions
appropriately using chmod() or fchmod() (Section 15.4.7).
When displaying permissions for a file whose permission bits are set for man-
datory locking, ls(1) displays an S in the group-execute permission column:

$ ls -l /testfs/file
-rw-r-Sr-- 1 mtk users 0 Apr 22 14:11 /testfs/file

Mandatory locking is supported for all native Linux and UNIX file systems, but
may not be supported on some network file systems or on non-UNIX file systems.
For example, Microsoft’s VFAT file system has no set-group-ID permission bit, so
mandatory locking can’t be used on VFAT file systems.

Effect of mandatory locking on file I/O operations
If mandatory locking is enabled for a file, what happens when a system call that per-
forms data transfer (e.g., read() or write()) encounters a lock conflict (i.e., an
attempt is made to write to a region that is currently read or write locked, or to
read from a region that is currently write locked)? The answer depends on whether
the file has been opened in blocking or nonblocking mode. If the file was opened
Free download pdf