BSD 4_2 development
[unix-history] / usr / man / man2 / flock.2
CommitLineData
48672018
C
1.TH FLOCK 2 "27 July 1983"
2.UC 4
3.SH NAME
4flock \- apply or remove an advisory lock on an open file
5.SH SYNOPSIS
6.nf
7.ft B
8#include <sys/file.h>
9.PP
10.ft B
11.DT
12#define LOCK_SH 1 /* shared lock */
13#define LOCK_EX 2 /* exclusive lock */
14#define LOCK_NB 4 /* don't block when locking */
15#define LOCK_UN 8 /* unlock */
16.PP
17.ft B
18flock(fd, operation)
19int fd, operation;
20.fi
21.SH DESCRIPTION
22.I Flock
23applies or removes an
24.I advisory
25lock on the file associated with the file descriptor
26.IR fd .
27A lock is applied by specifying an
28.I operation
29parameter which is the inclusive or of
30LOCK_SH or LOCK_EX and, possibly, LOCK_NB. To unlock
31an existing lock
32.I operation
33should be LOCK_UN.
34.PP
35Advisory locks allow cooperating processes to perform
36consistent operations on files, but do not guarantee
37consistency (i.e. processes may still access files
38without using advisory locks possibly resulting in
39inconsistencies).
40.PP
41The locking mechanism allows two types of locks:
42.I shared
43locks and
44.I exclusive
45locks.
46At any time multiple shared locks may be applied to a file,
47but at no time are multiple exclusive, or both shared and exclusive,
48locks allowed simultaneously on a file.
49.PP
50A shared lock may be
51.I upgraded
52to an exclusive lock, and vice versa, simply by specifying
53the appropriate lock type; this results in the previous
54lock being released and the new lock applied (possibly
55after other processes have gained and released the lock).
56.PP
57Requesting a lock on an object which is already locked
58normally causes the caller to blocked until the lock may be
59acquired. If LOCK_NB is included in
60.IR operation ,
61then this will not happen; instead the call will fail and
62the error EWOULDBLOCK will be returned.
63.SH NOTES
64Locks are on files, not file descriptors. That is, file descriptors
65duplicated through
66.IR dup (2)
67or
68.IR fork (2)
69do not result in multiple instances of a lock, but rather multiple
70references to a single lock. If a process holding a lock on a file
71forks and the child explicitly unlocks the file, the parent will
72lose its lock.
73.PP
74Processes blocked awaiting a lock may be awakened by signals.
75.SH "RETURN VALUE
76Zero is returned if the operation was successful;
77on an error a \-1 is returned and an error code is left in
78the global location \fIerrno\fP.
79.SH "ERRORS
80The \fIflock\fP call fails if:
81.TP 20
82[EWOULDBLOCK]
83The file is locked and the LOCK_NB option was specified.
84.TP 20
85[EBADF]
86The argument \fIfd\fP is an invalid descriptor.
87.TP 20
88[EINVAL]
89The argument \fIfd\fP refers to an object other than a file.
90.SH "SEE ALSO"
91open(2), close(2), dup(2), execve(2), fork(2)