lockf()

NAME

lockf() - lock sections of file with advisory-mode locks

SYNOPSIS

#include <unistd.h>

int lockf(int fd, int function, off_t size)

DESCRIPTION

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).

The lockf(3) function takes three arguments:

fd
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.

RETURN VALUES

The lockf(3) function returns 0 on success. It returns -1 on failure and sets errno; existing locks are not changed.

NOTES

This implementation of the lockf(3) function is a wrapper around the fcntl(2) function, using F_SETLK, F_SETLKW, and F_GETLK.

ERRORS

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.

SEE ALSO

alarm(2)

chmod(2)

close(2)

creat(3)

fcntl(2)

flock(2)

mmap(2)

open(2)

read(2)

write(2)