I want to test mandatory locking in linux (Ubuntu 22.04.2 LTS) and I do the following steps
1- mount /dev/vgg1/lvv11 /u03 -o mand
2- chmod g+s /u03/datafile.dbf
3- chmod g-x /u03/datafile.dbf
and then execute the following code:
struct flock lock;
.....
fd = open("/u03/datafile.dbf", O_RDWR);
lock.l_type = F_WRLCK;
lock.l_start = 40;
lock.l_whence = SEEK_SET;
lock.l_len = 12;
err=fcntl(fd, F_SETLK, &lock);
but as the output of lslocks, as following , shows that means lock type is not mandatory!
COMMAND PID TYPE SIZE MODE M START END PATH
llock 466440 POSIX 378B WRITE 0 40 51 /u03/datafile.dbf
cron 130607 FLOCK 7B WRITE 0 0 0 /run/crond.pid
what should I do to obtain mandatory lock?
This option, while it existed, required, as documented to mount the filesystem with
-o mandand have setgid set and execute not set. OP did all of these.But still as documented this feature has always had issues on Linux. The very first paragraph (0.) on the documentation explains why mandatory locking should be avoided and gives an example outcome where after a process gained mandatory lock, data could still be written by an other process due to race conditions, breaking the contract of a mandatory lock.
This feature (which appeared in kernel 4.5) was completely removed in kernel 5.15 with this commit:
Indeed, if you run
dmesgafter having used for the first time the-o mandoption, you should get a big multi-line warning message telling support was removed.Example on a system using Linux 6.6.x that didn't use
-o mandsince boot:So you have to run an older kernel with this feature enabled to get to use it. Examples of still (but not for long) supported Linux distributions with this feature enabled
Debian 11 (LTS till 2026-06-30)
Ships with kernel 5.10.x with
CONFIG_MANDATORY_FILE_LOCKING=y.Ubuntu 20.04 LTS (till 2025-04)
Ships with kernel 5.4.x with
CONFIG_MANDATORY_FILE_LOCKING=y.Notes: 20.04.0x LTS might use newer kernels. 20.04.5 LTS uses 5.15 so won't qualify.
As written in commit, RHEL-like distributions dropped support early, so I don't expect any shipped kernels from them to have
CONFIG_MANDATORY_FILE_LOCKING=y. Rolling-release-based distributions will have newer kernels so won't have this feature either.If your software was expected to rely on this feature on Linux, its code will have to be changed to not rely on it anymore.