System Interface Guide

Selecting Advisory or Mandatory Locking

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 mandatory 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 two permission bits in the file mode, which indicates mandatory locking on the file. The two bits in the mode are .1./.../..0/... An individual file cannot simultaneously be enabled for mandatory locking and have the set-group-ID on execution bit set. Nor can an individual file be enabled for mandatory locking and for group 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.