To lock an entire file, set the offset to zero and set the size to zero.
There are several ways to set a lock on a file. 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) function. It tries to lock a file until one of the following happens:
The file is successfully locked
There is an error
MAX_TRY is exceeded, and the program gives up 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 a few structure variables.
Mapped files cannot be locked with flock(3UCB). See mmap(2). However, the multithread-oriented synchronization mechanisms (in either POSIX or Solaris styles) can be used with mapped files. See mutex(3THR), condition(3THR), semaphore(3THR), and rwlock(3THR).