#include <sys/fcntl.h> #define F_ULOCK 0 /* Unlock a previously locked section */ #define F_LOCK 1 /* Lock a section for exclusive use */ #define F_TLOCK 2 /* Test and lock a section (non-blocking) */ #define F_TEST 3 /* Test section for other process' locks */ int lockf(fd, cmd, size) int fd, cmd; long size;
A lock is obtained by specifying a cmd parameter of F_LOCK or F_TLOCK. To unlock an existing lock, the F_ULOCK cmd is used. F_TEST is used to detect if a lock by another process is present on the specified segment.
F_LOCK and F_TLOCK requests differ only by the action taken if the lock may not be immediately granted. F_TLOCK returns a -1 by the function and sets errno to EAGAIN if the section is already locked by another process. F_LOCK will cause the process to sleep until the lock may be granted or a signal is caught.
size is the number of contiguous bytes to be locked or unlocked. The lock starts at the current file offset in the file and extends forward for a positive size or backward for a negative size (preceding but not including the current offset). A segment need not be allocated to the file in order to be locked; however, a segment may not extend to a negative offset relative to the beginning of the file. If size is zero, the lock will extend from the current offset through the EOF. If such a lock starts at offset 0, then the entire file will be locked (regardless of future file extensions).
All locks associated with a file for a given process are removed when the file is closed or the process terminates. Locks are not inherited by the child process in a fork(2) system call.