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.