Go to main content

Oracle® Solaris 11.4 Programming Interfaces Guide

Exit Print View

Updated: November 2020
 
 

Using File and Record Locking

To lock the file elements, you can use the light weight synchronization mechanisms that are described in Multithreaded Programming Guide with mapped files.

Locking files prevents errors that can occur when several users try to update a file at the same time. You can lock a portion of a file.

File locking blocks access to an entire file. Record locking blocks access to a specified segment of the file. In Oracle Solaris, all files are a sequence of bytes of data: a record is a concept of the programs that use the file.

Choosing a Lock Type

Mandatory locking suspends a process until the requested file segments are free. Advisory locking returns a result indicating whether the lock was obtained or not. A process can ignore the result of advisory locking. You cannot use both mandatory and advisory file locking on the same file at the same time. The mode of a file at the time the file is opened determines whether locks on a file are treated as mandatory or advisory.

The fcntl locking call is more portable, powerful, and less easy to use than lockf locking call. fcntl is specified in POSIX 1003.1 standard. lockf is compatible with older applications. For more information, see the fcntl(2), lockf(3C), fcntl(2), and lockf(3C) man pages.

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 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);
 	}
 	... 

The operating system ignores record locks when the system is executing a file. Any files with record locks should not have execute permissions set.

The chmod command can also be used to set a file to permit mandatory locking. For more information, see the chmod(1) man page.

$ 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 command shows this setting when you ask for the long listing format with the –l option:

$ ls -l file

This command displays the 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. Because the set-group-ID bit is on, mandatory locking is enabled. Normal semantics of set-group-ID are also enabled.

For more information, see the ls(1) man page.

Cautions About Mandatory Locking

    Keep in mind the following aspects of locking:

  • Mandatory locking works only for local files. Mandatory locking is not supported when accessing files through NFS.

  • Mandatory locking protects only the segments of a file that are locked. The remainder of the file can be accessed according to normal file permissions.

  • If multiple reads or writes are needed for an atomic transaction, the process should explicitly lock all such segments before any I/O begins. Advisory locks are sufficient for all programs that perform in this way.

  • Arbitrary programs should not have unrestricted access permission to files on which record locks are used.

  • Advisory locking is more efficient because a record lock check does not have to be performed for every I/O request.

Supported File Systems

Both advisory and mandatory locking are supported on the file systems listed in the following table.

Table 4  Supported File Systems
File System
Description
ufs
The disk-based file system
fifofs
A pseudo file system of named pipe files that give processes common access to data
namefs
A pseudo file system used mostly by STREAMS for dynamic mounts of file descriptors on top of file
specfs
A pseudo file system that provides access to special character devices and block devices
zfs
A transactional file system that uses the concept of storage pools to manage physical storage. For more information, see Managing ZFS File Systems in Oracle Solaris 11.4.

Only advisory file locking is supported on NFS. File locking is not supported for the proc and fd file systems.

Opening a File for Locking

You can only request a lock for a file with a valid open descriptor. For read locks, the file must be open with at least read access. For write locks, the file must also be open with write access. In the following example, a file is opened for both read and write access.

...
 	filename = argv[1];
 	fd = open (filename, O_RDWR);
 	if (fd < 0) {
 		perror(filename);
 		exit(2);
 	}
 	...

Setting a File Lock

To lock an entire file, set the offset to zero and set the size to zero.

You can set a lock on a file in several ways. The choice of method depends on how the lock interacts with the rest of the program, performance, and portability. This example uses the POSIX standard-compatible fcntl() interface. The interface tries to lock a file until one of the following events happen:

  • The file lock is set successfully

  • An error occurs

  • MAX_TRY is exceeded, and the program stops trying to lock the file

    #include <fcntl.h>
    
     ...
     	struct flock lck;
    
     ...
     	lck.l_type = F_WRLCK;	/* setting a write lock */
     	lck.l_whence = 0;	/* offset l_start from beginning of file */
     	lck.l_start = (off_t)0;	
     	lck.l_len = (off_t)0;	/* until the end of the file */
     	if (fcntl(fd, F_SETLK, &lck) <0) {
     		if (errno == EAGAIN || errno == EACCES) {
     			(void) fprintf(stderr, "File busy try again later!\n");
     			return;
     		}
     		perror("fcntl");
     		exit (2);
     	}
     	...

    Using fcntl(), you can set the type and start of the lock request by setting structure variables. For more information, see the fcntl(2) man page.


    Note -  You cannot lock mapped files with flock. However, you can use the multithread-oriented synchronization mechanisms with mapped files. These synchronization mechanisms can be used in POSIX styles and in Oracle Solaris styles.

Setting and Removing Record Locks

When locking a record, do not set the starting point and length of the lock segment to zero. The locking procedure is otherwise identical to file locking.

Contention for data is why you use record locking. Therefore, you must have a failure response for when you cannot obtain all the required locks:

  • Wait a certain amount of time, then try again

  • Abort the procedure, warn the user

  • Let the process sleep until signaled that the lock has been freed

  • Do some combination of the previous

This example shows a record being locked by using fcntl.

{
 	struct flock lck;
   	...
 	lck.l_type = F_WRLCK;	/* setting a write lock */
 	lck.l_whence = 0;	/* offset l_start from beginning of file */
 	lck.l_start = here;
 	lck.l_len = sizeof(struct record);

 	/* lock "this" with write lock */
 	lck.l_start = this;
 	if (fcntl(fd, F_SETLKW, &lck) < 0) {
 		/* "this" lock failed. */
 		return (-1);
 ...
}

The next example shows the usage of lockf interface.

#include <unistd.h>

{
 ...
 	/* lock "this" */
 	(void) lseek(fd, this, SEEK_SET);
 	if (lockf(fd, F_LOCK, sizeof(struct record)) < 0) {
 		/* Lock on "this" failed. Clear lock on "here". */
 		(void) lseek(fd, here, 0);
 		(void) lockf(fd, F_ULOCK, sizeof(struct record));
 		return (-1);
}
 

You remove locks in the same way the locks were set. Only the lock type is different (F_ULOCK). An unlock cannot be blocked by another process and affects only locks placed by the calling process. The unlock affects only the segment of the file specified in the preceding locking call.

Getting Lock Information

You can determine which process is holding a lock. A lock is set, as in the previous examples, and F_GETLK is used in fcntl.

The next example finds and prints identifying data on all the locked segments of a file.

Example 18  Printing Locked Segments of a File
struct flock lck;

 	lck.l_whence = 0;
 	lck.l_start = 0L;
 	lck.l_len = 0L;
 	do {
 		lck.l_type = F_WRLCK;
 		(void) fcntl(fd, F_GETLK, &lck);
 		if (lck.l_type != F_UNLCK) {
 			(void) printf("%d %d %c %8ld %8ld\n", lck.l_sysid, lck.l_pid,
            (lck.l_type == F_WRLCK) ? 'W' : 'R', lck.l_start, lck.l_len);
 			/* If this lock goes to the end of the address space, no
 			 * need to look further, so break out. */
 			if (lck.l_len == 0) {
 			/* else, look for new lock after the one just found. */
 					lck.l_start += lck.l_len;
 			}
 		}
 	} while (lck.l_type != F_UNLCK);

fcntl with the F_GETLK command can sleep while waiting for a server to respond. The command can fail, returning ENOLCK, if either the client or the server have a resource shortage.

Use lockf() with the F_TEST command to test if a process is holding a lock. This interface does not return information about the lock's location or ownership. For more information, see the lockf(3C) man page.

Example 19  Testing a Process With lockf()
(void) lseek(fd, 0, 0L);
 /* set the size of the test region to zero (0). to test until the
    end of the file address space. */
if (lockf(fd, (off_t)0, SEEK_SET) < 0) {
    switch (errno) {
        case EACCES:
        case EAGAIN:
            (void) printf("file is locked by another process\n");
            break;
        case EBADF:
            /* bad argument passed to lockf */
            perror("lockf");
            break;
        default:
            (void) printf("lockf: unexpected error <%d>\n", errno);
            break;
    }
}

Process Forking and Locks

When a process forks, the child receives a copy of the file descriptors that the parent opened. Locks are not inherited by the child because the locks are owned by a specific process. The parent and child share a common file pointer for each file. Both processes can try to set locks on the same location in the same file. This problem occurs with both lockf() and fcntl(). If a program holding a record lock forks, the child process should close the file. After closing the file, the child process should reopen the file to set a new, separate file pointer. For more information, see the lockf(3C) and fcntl(2) man pages.

Deadlock Handling

The UNIX locking facilities provide deadlock detection and avoidance. Deadlocks can occur only when the system is ready to put a record-locking interface to sleep. A search is made to determine whether two processes are in a deadlock. If a potential deadlock is detected, the locking interface fails and sets errno to indicate deadlock. Processes setting locks that use F_SETLK do not cause a deadlock because these processes do not wait when the lock cannot be granted immediately.