The lockf(3) function can be used to lock sections of
a file with advisory-mode locks. If another process uses lockf(3) to lock
an already-locked section of the file, lockf(3) will return an error or
block (depending upon function).
An open file descriptor. In order to establish a lock, the file
must have been opened with either write-only permission or
read/write permission (O_WRONLY or O_RDWR).
function
The action to be taken by lockf(3). The following values for
function are defined in <unistd.h>:
F_LOCK
Lock a section for exclusive use. The calling process is
blocked until the section is available. (Blocking on a section is
interrupted by any signal.)
F_TEST
Test a section for locks by other processes.
F_TLOCK
Test and lock a section for exclusive use. The function fails
if the section is not available.
F_ULOCK
Unlock all or part of a locked sections. File locks are also
released the first time any file descriptor for the file is closed
by the calling process. If the middle part of a locked section is
unlocked, it leaves behind two separate locked sections.
size
The number of continguous bytes to be locked or unlocked. If
size is positive, size bytes will be locked (or
unlocked) starting at the current offset in the file; if
size is negative, size bytes will be locked (or
unlocked) ending at the current offset in the file. If size
is 0, the lockf(3) function locks from the current offset
to the present or any future end-of-file.
Sections locked may overlap, contain, or be contained by another
section already locked by the same process. In this case, the
sections are combined into a single locked section.
The (3) function can fail for the following
reasons:
[EACCES]
The function is F_TLOCK or F_TEST and the section is
already locked by another process.
[EAGAIN]
The function attempted to lock a file that is mapped with
mmap(2).
[EBADF]
The file descriptor is not a valid open file descriptor, or the
call is trying to lock the file (F_LOCK or F_TLOCK) and the file
isn't open for writing.
[EINTR]
A signal interrupted the execution of the function.
[EINVAL]
The function argument is not one of the ones defined
here, or size plus the current offset is less than zero or
is greater than the largest possible offset.
[EOPNOTSUPP]
This implementation does not support the locking of files of
the type indicated by the file descriptor.