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(2) interface. The interface tries to lock a file until one of the following happens:
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(2), you can set the type and start of the lock request by setting structure variables.
You cannot lock mapped files with flock(3UCB). However, you can use the multithread-oriented synchronization mechanisms with mapped files. These synchronization mechanisms can be used in POSIX styles as well as in Solaris styles.