FCNTL(2)
π FCNTL(2) π
πΈ NAME πΈ
fcntl β file control
bestie, this is the file control page, aka FCNTL(2). it's literally the main character of descriptor manipulation. no cap. π
π LIBRARY π
Standard C Library (libc, -lc)
β¨ SYNOPSIS β¨
#include <fcntl.h>
int
fcntl(int fd, int cmd, ...);
π¦ DESCRIPTION π¦
okay so fcntl() is the system call that gives you control over descriptors. the argument fd is the descriptor that cmd is gonna operate on, as described below. depending on what cmd is, fcntl() can take an extra third argument, int arg.
π The Commands π
F_DUPFDβ this one returns a new descriptor, and here's the tea:- it's the lowest numbered available descriptor greater than or equal to
arg. - it has the same object references as the original descriptor.
- if the object was a file, the new descriptor shares the same file offset.
- same access mode (read, write or read/write).
- same file status flags (i.e., both file descriptors share the same file status flags).
- the close-on-exec flag
FD_CLOEXECassociated with the new file descriptor is cleared, so the file descriptor is to remain open acrossexecve(2)system calls.
- it's the lowest numbered available descriptor greater than or equal to
F_DUPFD_CLOEXECβ just likeF_DUPFD, but theFD_CLOEXECflag associated with the new file descriptor is set, so the file descriptor is closed whenexecve(2)system call executes.F_DUP2FDβ it's functionally equivalent to
dup2(fd, arg)
F_DUP2FD_CLOEXECβ likeF_DUP2FD, but theFD_CLOEXECflag associated with the new file descriptor is set.
heads up: theF_DUP2FDandF_DUP2FD_CLOEXECconstants are not portable, so don't use them if you need portability. usedup2()instead ofF_DUP2FD.
F_GETFDβ gets the close-on-exec flag associated with the file descriptorfdasFD_CLOEXEC. if the returned value ANDed withFD_CLOEXECis 0, the file will remain open acrossexec(), otherwise the file will be closed upon execution ofexec()(argis ignored).F_SETFDβ sets the close-on-exec flag associated withfdtoarg, whereargis either 0 orFD_CLOEXEC, as described above.F_GETFLβ gets descriptor status flags, as described below (argis ignored).F_SETFLβ sets descriptor status flags toarg.F_GETOWNβ gets the process ID or process group currently receivingSIGIOandSIGURGsignals; process groups are returned as negative values (argis ignored).F_SETOWNβ sets the process or process group to receiveSIGIOandSIGURGsignals; process groups are specified by supplyingargas negative, otherwiseargis interpreted as a process ID.F_READAHEADβ sets or clears the read ahead amount for sequential access to the third argument,arg, which is rounded up to the nearest block size. a zero value inargturns off read ahead, a negative value restores the system default.F_RDAHEADβ equivalent to Darwin counterpart which sets read ahead amount of 128KB when the third argument,argis non-zero. a zero value inargturns off read ahead.
π The Flags for F_GETFL and F_SETFL π
the flags for the F_GETFL and F_SETFL flags are as follows:
O_NONBLOCKβ non-blocking I/O; if no data is available to aread(2)system call, or if awrite(2)operation would block, the read or write call returns -1 with the errorEAGAIN.O_APPENDβ force each write to append at the end of file; corresponds to theO_APPENDflag ofopen(2).O_DIRECTβ minimize or eliminate the cache effects of reading and writing. the system will attempt to avoid caching the data you read or write. if it cannot avoid caching the data, it will minimize the impact the data has on the cache. use of this flag can drastically reduce performance if not used with care.O_ASYNCβ enable theSIGIOsignal to be sent to the process group when I/O is possible, e.g., upon availability of data to be read.
π Advisory File Locking π
several commands are available for doing advisory file locking; they all operate on the following structure:
struct flock {
off_t l_start; /* starting offset */
off_t l_len; /* len = 0 means until end of file */
pid_t l_pid; /* lock owner */
short l_type; /* lock type: read/write, etc. */
short l_whence; /* type of l_start */
int l_sysid; /* remote system id or zero for local */
};
the commands available for advisory record locking are as follows:
F_GETLKβ get the first lock that blocks the lock description pointed to by the third argument,arg, taken as a pointer to astruct flock(see above). the information retrieved overwrites the information passed tofcntl()in the flock structure. if no lock is found that would prevent this lock from being created, the structure is left unchanged by this system call except for the lock type which is set toF_UNLCK.F_SETLKβ set or clear a file segment lock according to the lock description pointed to by the third argument,arg, taken as a pointer to astruct flock(see above).F_SETLKis used to establish shared (or read) locks (F_RDLCK) or exclusive (or write) locks, (F_WRLCK), as well as remove either type of lock (F_UNLCK). if a shared or exclusive lock cannot be set,fcntl()returns immediately withEAGAIN.F_SETLKWβ this command is the same asF_SETLKexcept that if a shared or exclusive lock is blocked by other locks, the process waits until the request can be satisfied. if a signal that is to be caught is received whilefcntl()is waiting for a region, thefcntl()will be interrupted if the signal handler has not specified theSA_RESTART(seesigaction(2)).
when a shared lock has been set on a segment of a file, other processes can set shared locks on that segment or a portion of it. a shared lock prevents any other process from setting an exclusive lock on any portion of the protected area. a request for a shared lock fails if the file descriptor was not opened with read access.
an exclusive lock prevents any other process from setting a shared lock or an exclusive lock on any portion of the protected area. a request for an exclusive lock fails if the file was not opened with write access.
the value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END to indicate that the relative offset, l_start bytes, will be measured from the start of the file, current position, or end of the file, respectively. the value of l_len is the number of consecutive bytes to be locked. if l_len is negative, l_start means end edge of the region. the l_pid and l_sysid fields are only used with F_GETLK to return the process ID of the process holding a blocking lock and the system ID of the system that owns that process. locks created by the local system will have a system ID of zero. after a successful F_GETLK request, the value of l_whence is SEEK_SET.
locks may start and extend beyond the current end of a file, but may not start or extend before the beginning of the file. a lock is set to extend to the largest possible value of the file offset for that file if l_len is set to zero. if l_whence and l_start point to the beginning of the file, and l_len is zero, the entire file is locked. if an application wishes only to do entire file locking, the flock(2) system call is much more efficient.
there is at most one type of lock set for each byte in the file. before a successful return from an F_SETLK or an F_SETLKW request when the calling process has previously existing locks on bytes in the region specified by the request, the previous lock type for each byte in the specified region is replaced by the new lock type. as specified above under the descriptions of shared locks and exclusive locks, an F_SETLK or an F_SETLKW request fails or blocks respectively when another process has existing locks on bytes in the specified region and the type of any of those locks conflicts with the type specified in the request.
the queuing for F_SETLKW requests on local files is fair; that is, while the thread is blocked, subsequent requests conflicting with its requests will not be granted, even if these requests do not conflict with existing locks.
this interface follows the completely stupid semantics of System V and IEEE Std 1003.1-1988 (βPOSIX.1β) that require that all locks associated with a file for a given process are removed when any file descriptor for that file is closed by that process. this semantic means that applications must be aware of any files that a subroutine library may access. for example if an application for updating the password file locks the password file database while making the update, and then calls getpwnam(3) to retrieve a record, the lock will be lost because getpwnam(3) opens, reads, and closes the password database. the database close will release all locks that the process has associated with the database, even if the library routine never requested a lock on the database. another minor semantic problem with this interface is that locks are not inherited by a child process created using the fork(2) system call. the flock(2) interface has much more rational last close semantics and allows locks to be inherited by child processes. the flock(2) system call is recommended for applications that want to ensure the integrity of their locks when using library routines or wish to pass locks to their children.
the fcntl(), flock(2), and lockf(3) locks are compatible. processes using different locking interfaces can cooperate over the same file safely. however, only one of such interfaces should be used within the same process. if a file is locked by a process through flock(2), any record within the file will be seen as locked from the viewpoint of another process using fcntl() or lockf(3), and vice versa. note that fcntl(F_GETLK) returns -1 in l_pid if the process holding a blocking lock previously locked the file descriptor by flock(2).
All locks associated with a file for a given process are removed when the process terminates.
Okay so bestie, when a process dips out? Every lock it had on a file? Gone. Poof. β¨
All locks obtained before a call to execve(2) remain in effect until the new program releases them. If the new program does not know about the locks, they will not be released until the program exits.
Like, if you lock stuff and then execve(2) into a new program, those locks are still holding on. If the new program has no idea they exist, it won't unlock them β they stay until it exits. The way that is so real and also lowkey terrifying. π
A potential for deadlock occurs if a process controlling a locked region is put to sleep by attempting to lock the locked region of another process. This implementation detects that sleeping until a locked region is unlocked would cause a deadlock and fails with an EDEADLK error.
Deadlock tea: if a process already owns a locked region and then goes to sleep trying to lock another process's locked region, that's the setup. This implementation is like βbestie noβ β it detects that waiting for the lock to free up would deadlock, and fails with EDEADLK. Periodt. π
β¨ RETURN VALUES β¨
Upon successful completion, the value returned depends on cmd as follows:
F_DUPFDβ A new file descriptor. πF_DUP2FDβ A file descriptor equal toarg.F_GETFDβ Value of flag (only the low-order bit is defined).F_GETFLβ Value of flags.F_GETOWNβ Value of file descriptor owner.- other β Value other than
-1.
Otherwise, a value of -1 is returned and errno is set to indicate the error.
π¨ ERRORS π¨
The fcntl() system call will fail if:
[EAGAIN]β The argumentcmdisF_SETLK, the type of lock (l_type) is a shared lock (F_RDLCK) or exclusive lock (F_WRLCK), and the segment of a file to be locked is already exclusive-locked by another process; or the type is an exclusive lock and some portion of the segment of a file to be locked is already shared-locked or exclusive-locked by another process. π[EBADF]β Thefdargument is not a valid open file descriptor.
The argument cmd is F_DUP2FD, and arg is not a valid file descriptor.
The argument cmd is F_SETLK or F_SETLKW, the type of lock (l_type) is a shared lock (F_RDLCK), and fd is not a valid file descriptor open for reading.
The argument cmd is F_SETLK or F_SETLKW, the type of lock (l_type) is an exclusive lock (F_WRLCK), and fd is not a valid file descriptor open for writing.
[EDEADLK]β The argumentcmdisF_SETLKW, and a deadlock condition was detected.[EINTR]β The argumentcmdisF_SETLKW, and the system call was interrupted by a signal.[EINVAL]β Thecmdargument isF_DUPFDandargis negative or greater than the maximum allowable number (seegetdtablesize(2)).
The argument cmd is F_GETLK, F_SETLK or F_SETLKW and the data to which arg points is not valid.
The argument cmd is invalid.
[EMFILE]β The argumentcmdisF_DUPFDand the maximum number of file descriptors permitted for the process are already in use, or no file descriptors greater than or equal toargare available.[ENOTTY]β Thefdargument is not a valid file descriptor for the requested operation. This may be the case iffdis a device node, or a descriptor returned bykqueue(2).[ENOLCK]β The argumentcmdisF_SETLKorF_SETLKW, and satisfying the lock or unlock request would result in the number of locked regions in the system exceeding a system-imposed limit.[EOPNOTSUPP]β The argumentcmdisF_GETLK,F_SETLKorF_SETLKWandfdrefers to a file for which locking is not supported.[EOVERFLOW]β The argumentcmdisF_GETLK,F_SETLKorF_SETLKWand anoff_tcalculation overflowed.[EPERM]β Thecmdargument isF_SETOWNand the process ID or process group given as an argument is in a different session than the caller.[ESRCH]β Thecmdargument isF_SETOWNand the process ID given as argument is not in use.
In addition, if fd refers to a descriptor open on a terminal device (as opposed to a descriptor open on a socket), a cmd of F_SETOWN can fail for the same reasons as in tcsetpgrp(3), and a cmd of F_GETOWN for the reasons as stated in tcgetpgrp(3).
π SEE ALSO π
close(2), dup2(2), execve(2), flock(2), getdtablesize(2), open(2), sigaction(2), lockf(3), tcgetpgrp(3), tcsetpgrp(3)
π STANDARDS π
The F_DUP2FD constant is non portable. It is provided for compatibility with AIX and Solaris.
Per Version 4 of the Single UNIX Specification (βSUSv4β), a call with F_SETLKW should fail with [EINTR] after any caught signal and should continue waiting during thread suspension such as a stop signal. However, in this implementation a call with F_SETLKW is restarted after catching a signal with a SA_RESTART handler or a thread suspension such as a stop signal.
π¦ HISTORY π¦
The fcntl() system call appeared in 4.2BSD.
The F_DUP2FD constant first appeared in FreeBSD 7.1.
And that's the whole vibe, bestie! This page is from Debian, dated Nov 15, 2018, and it's FCNTL(2). Stay locked and loaded (the legal kind), mwah ππ«Ά
π¦ where this page comes from
- debian bookworm: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- debian trixie: freebsd-manpages 12.2-2 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu jammy: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu noble: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu questing: freebsd-manpages 12.2-2
- ubuntu resolute: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu stonking: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- Copyright (c) 1983, 1993 The Regents of the University of California. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms