For mandatory locks, the file must be a regular file with the set-group-ID bit on and the group execute permission off. If either condition fails, all record locks are advisory. Set a mandatory lock as follows.
#include <sys/types.h> #include <sys/stat.h> int mode; struct stat buf; ... if (stat(filename, &buf) < 0) { perror("program"); exit (2); } /* get currently set mode */ mode = buf.st_mode; /* remove group execute permission from mode */ mode &= ~(S_IEXEC>>3); /* set 'set group id bit' in mode */ mode |= S_ISGID; if (chmod(filename, mode) < 0) { perror("program"); exit(2); } ...
Files to be record locked should never have any execute permission set. This is because the operating system ignores record locks when executing a file.
The chmod(1) command can also be used to set a file to permit mandatory locking. For example:
$ chmod +l file
This command sets the O20n0 permission bit in the file mode, which indicates mandatory locking on the file. If n is even, the bit is interpreted as enabling mandatory locking. If n is odd, the bit is interpreted as "set group ID on execution."
The ls(1) command shows this setting when you ask for the long listing format with the -l option:
$ ls -l file |
displays following information:
-rw---l--- 1 user group size mod_time file |
The letter "l" in the permissions indicates that the set-group-ID bit is on, so mandatory locking is enabled, along with the normal semantics of set group ID.