.TH lockf() "" "" "General Function (libc)"
.PC "Lock a file or a section of a file"
.B "#include <unistd.h>"
\fBint\fR
\fBlockf(\fIfd\^\fB, \fIcmd\^\fB, \fIsize\^\fB)\fR
\fBint \fIfd\^\fB, \fIcmd\^\fB; long \fIsize\^\fB;\fR
.PP
.II "locking^file"
.II "file^locking"
.II "flock"
.II "fcntl.h"
The \*(CO library function
.B lockf()
allows a process to lock part or all of a file.
If another process calls
.B lockf()
on the same file
to request a lock that conflicts with a previous lock, the later
.B lockf()
call returns an error or sleeps until the file
is unlocked by the first process.
.PP
.I fd
gives a file descriptor of an open file;
the file must have been opened with
.B O_WRONLY
or
.B O_RDWR
permission if
.B lockf()
is to succeed.
.PP
.I size
specifies how many bytes should be locked or unlocked.
The lock begins at the current file position and extend
forward (if \fIsize\fR is positive)
or backwards (if it is negative).
A
.I size
of zero locks or unlocks the entire file starting from the current position.
.PP
.I cmd
specifies the action
.B lockf()
is to take.
.B lockf()
recognizes the following four commands, as specified in the header file
.BR <unistd.h> :
.II unistd.h
.IP \fBF_TEST\fR 0.8i
Test whether a lock has already been set
upon the specified section of the file.
.IP \fBF_LOCK\fR
Lock a section of the file, if possible.
If the section cannot be locked,
sleep until it becomes available for locking.
.IP \fBF_TLOCK\fR
Lock a section of the file, if possible.
Unlike
.B F_LOCK,
.B F_TLOCK
does not sleep if the section cannot be locked;
rather, it returns -1 and sets
.B errno
to
.B EAGAIN
if the lock is not available.
.IP \fBF_ULOCK\fR
Unlock a currently existing lock.
.PP
Use
.B lockf()
with the unbuffered I/O routines
(\fBopen()\fR, \fBwrite()\fR, and so on)
rather than with standard I/O library routines
(\fBfopen()\fR, \fBfprintf()\fR, \fBfwrite()\fR, and so on).
The buffering used by the standard I/O library may
cause unexpected behavior with file locking.
.SH "See Also"
.Xr "creat()," creat
.Xr "fcntl()," fcntl
.Xr "libc," libc
.Xr "open()" open
.SH Diagnostics
.B lockf()
returns zero on success, \-1 on failure.
On failure, it also sets
.B errno
to an appropriate value.
Possible errors include the following:
.IP \fBEINVAL\fR 0.8i
Invalid file descriptor.
.IP \fBEAGAIN\fR
Requested section is already locked.
.IP \fBEDEADLK\fR
A deadlock would occur if the command slept,
or the system lock table is full.
.SH Notes
See the Lexicon entry for
.B fcntl()
for a fuller description of the \*(CO system's method of file locking.
