1FLOCK(2) System Calls Manual FLOCK(2)
2
3
4
6 flock - apply or remove an advisory lock on an open file
7
9 #include <sys/file.h>
10
11 #define LOCK_SH 1 /* shared lock */
12 #define LOCK_EX 2 /* exclusive lock */
13 #define LOCK_NB 4 /* don't block when locking */
14 #define LOCK_UN 8 /* unlock */
15
16 flock(fd, operation)
17 int fd, operation;
18
20 Flock applies or removes an advisory lock on the file associated with
21 the file descriptor fd. A lock is applied by specifying an operation
22 parameter that is the inclusive or of LOCK_SH or LOCK_EX and, possibly,
23 LOCK_NB. To unlock an existing lock operation should be LOCK_UN.
24
25 Advisory locks allow cooperating processes to perform consistent opera‐
26 tions on files, but do not guarantee consistency (i.e., processes may
27 still access files without using advisory locks possibly resulting in
28 inconsistencies).
29
30 The locking mechanism allows two types of locks: shared locks and
31 exclusive locks. At any time multiple shared locks may be applied to a
32 file, but at no time are multiple exclusive, or both shared and exclu‐
33 sive, locks allowed simultaneously on a file.
34
35 A shared lock may be upgraded to an exclusive lock, and vice versa,
36 simply by specifying the appropriate lock type; this results in the
37 previous lock being released and the new lock applied (possibly after
38 other processes have gained and released the lock).
39
40 Requesting a lock on an object that is already locked normally causes
41 the caller to be blocked until the lock may be acquired. If LOCK_NB is
42 included in operation, then this will not happen; instead the call will
43 fail and the error EWOULDBLOCK will be returned.
44
46 Locks are on files, not file descriptors. That is, file descriptors
47 duplicated through dup(2) or fork(2) do not result in multiple
48 instances of a lock, but rather multiple references to a single lock.
49 If a process holding a lock on a file forks and the child explicitly
50 unlocks the file, the parent will lose its lock.
51
52 Processes blocked awaiting a lock may be awakened by signals.
53
55 Zero is returned if the operation was successful; on an error a -1 is
56 returned and an error code is left in the global location errno.
57
59 The flock call fails if:
60
61 [EWOULDBLOCK] The file is locked and the LOCK_NB option was spec‐
62 ified.
63
64 [EBADF] The argument fd is an invalid descriptor.
65
66 [EINVAL] The argument fd refers to an object other than a
67 file.
68
70 open(2), close(2), dup(2), execve(2), fork(2)
71
72
73
744.2 Berkeley Distribution May 22, 1986 FLOCK(2)