flock(2)flock(2)Nameflock - apply or remove an advisory lock on an open file
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
int fd, operation;
The system call applies or removes an advisory lock on the file associ‐
ated with the file descriptor, fd. A lock is applied by specifying an
operation parameter that is the inclusive OR of LOCK_SH or LOCK_EX and,
possibly, LOCK_NB. To unlock an existing lock, operation should be
Advisory locks allow cooperating processes to perform consistent opera‐
tions on files, but do not guarantee consistency; that is, processes
might still access files without using advisory locks, possibly result‐
ing in inconsistencies.
The locking mechanism allows two types of locks: shared locks and
exclusive locks. At any time, multiple shared locks can be applied to
a file. However, multiple exclusive locks, or shared and exclusive
locks cannot be applied simultaneously on a file.
A shared lock can be upgraded to be an exclusive lock, and an exclusive
lock can become shared, simply by specifying the appropriate lock type.
This change results in the previous lock being released and the new
lock applied. When upgrading, do not include LOCK_NB in operation,
because there is a possibility that other processes have requests for
locks, or have gained or released a lock.
Requesting a lock on an object that is already locked normally causes
the caller to blocked until the lock can be acquired. If LOCK_NB is
included in operation, the call is not blocked; instead, the call fails
and the error EWOULDBLOCK is returned.
Locks are on files, not file descriptors. That is, file descriptors
duplicated through or call do not result in multiple instances of a
lock, but rather multiple references to a single lock. If a process
holding a lock on a file forks and the child explicitly unlocks the
file, the parent loses its lock.
Processes blocked awaiting a lock may be awakened by signals.
Zero is returned if the operation was successful; on an error, a -1 is
returned and an error code is stored in the global variable, errno.
The call fails under the following conditions:
[EWOULDBLOCK] The file is locked and the LOCK_NB option was specified.
[EBADF] The argument fd is an invalid descriptor.
[EINVAL] The argument fd refers to an object other than a file.
[EOPNOTSUPP] Invalid operation is requested. The argument fd refers
to a socket.
File region locking is not supported over NFS.
See Alsoclose(2), dup(2), execve(2), fork(2), open(2)flock(2)