FCNTL(3P)
โจ PROLOG โจ
okay so bestie, vibe check: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (so go consult the corresponding Linux manual page for the details on Linux behavior, fr fr), or the interface may not be implemented on Linux at all. ๐
๐ธ NAME ๐ธ
fcntl โ file control ๐
โจ SYNOPSIS โจ
#include <fcntl.h>
int fcntl(int fildes, int cmd, ...);
๐ DESCRIPTION ๐
okay so the fcntl() function shall perform the operations described below on open files. The fildes argument is a file descriptor. no cap.
The available values for cmd are defined in <fcntl.h> and are as follows, bestie:
F_DUPFDโ Return a new file descriptor which shall be allocated as described in Section 2.14, File Descriptor Allocation, except that it shall be the lowest numbered available file descriptor greater than or equal to the third argument,arg, taken as an integer of typeint. The new file descriptor shall refer to the same open file description as the original file descriptor, and shall share any locks. TheFD_CLOEXECflag associated with the new file descriptor shall be cleared to keep the file open across calls to one of the exec functions. ๐ฆF_DUPFD_CLOEXECโ LikeF_DUPFD, but theFD_CLOEXECflag associated with the new file descriptor shall be set. slay.F_GETFDโ Get the file descriptor flags defined in<fcntl.h>that are associated with the file descriptorfildes. File descriptor flags are associated with a single file descriptor and do not affect other file descriptors that refer to the same file. periodt.F_SETFDโ Set the file descriptor flags defined in<fcntl.h>, that are associated withfildes, to the third argument,arg, taken as typeint. If theFD_CLOEXECflag in the third argument is0, the file descriptor shall remain open across the exec functions; otherwise, the file descriptor shall be closed upon successful execution of one of the exec functions. ๐F_GETFLโ Get the file status flags and file access modes, defined in<fcntl.h>, for the file description associated withfildes. The file access modes can be extracted from the return value using the maskO_ACCMODE, which is defined in<fcntl.h>. File status flags and file access modes are associated with the file description and do not affect other file descriptors that refer to the same file with different open file descriptions. The flags returned may include non-standard file status flags which the application did not set, provided that these additional flags do not alter the behavior of a conforming application. ๐F_SETFLโ Set the file status flags, defined in<fcntl.h>, for the file description associated withfildesfrom the corresponding bits in the third argument,arg, taken as typeint. Bits corresponding to the file access mode and the file creation flags, as defined in<fcntl.h>, that are set inargshall be ignored. If any bits inargother than those mentioned here are changed by the application, the result is unspecified. Iffildesdoes not support non-blocking operations, it is unspecified whether theO_NONBLOCKflag will be ignored. ๐F_GETOWNโ Iffildesrefers to a socket, get the process ID or process group ID specified to receiveSIGURGsignals when out-of-band data is available. Positive values shall indicate a process ID; negative values, other than-1, shall indicate a process group ID; the value zero shall indicate that noSIGURGsignals are to be sent. Iffildesdoes not refer to a socket, the results are unspecified. ๐F_SETOWNโ Iffildesrefers to a socket, set the process ID or process group ID specified to receiveSIGURGsignals when out-of-band data is available, using the value of the third argument,arg, taken as typeint. Positive values shall indicate a process ID; negative values, other than-1, shall indicate a process group ID; the value zero shall indicate that noSIGURGsignals are to be sent. Each time aSIGURGsignal is sent to the specified process or process group, permission checks equivalent to those performed bykill()shall be performed, as ifkill()were called by a process with the same real user ID, effective user ID, and privileges that the process callingfcntl()has at the time of the call; if thekill()call would fail, no signal shall be sent. These permission checks may also be performed by thefcntl()call. If the process specified byarglater terminates, or the process group specified byarglater becomes empty, while still being specified to receiveSIGURGsignals when out-of-band data is available fromfildes, then no signals shall be sent to any subsequently created process that has the same process ID or process group ID, regardless of permission; it is unspecified whether this is achieved by the equivalent of afcntl(fildes, F_SETOWN, 0)call at the time the process terminates or is waited for or the process group becomes empty, or by other means. Iffildesdoes not refer to a socket, the results are unspecified. ๐ญ
The following values for cmd are available for advisory record locking. Record locking shall be supported for regular files, and may be supported for other files. bestie, lock in ๐
F_GETLKโ Get any lock which blocks the lock description pointed to by the third argument,arg, taken as a pointer to typestruct flock, defined in<fcntl.h>. The information retrieved shall overwrite the information passed tofcntl()in the structureflock. If no lock is found that would prevent this lock from being created, then the structure shall be left unchanged except for the lock type which shall be 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 typestruct flock, defined in<fcntl.h>.F_SETLKcan establish shared (or read) locks (F_RDLCK) or exclusive (or write) locks (F_WRLCK), as well as to remove either type of lock (F_UNLCK).F_RDLCK,F_WRLCK, andF_UNLCKare defined in<fcntl.h>. If a shared or exclusive lock cannot be set,fcntl()shall return immediately with a return value of-1. ๐ฅF_SETLKWโ This command shall be equivalent toF_SETLKexcept that if a shared or exclusive lock is blocked by other locks, the thread shall wait until the request can be satisfied. If a signal that is to be caught is received whilefcntl()is waiting for a region,fcntl()shall be interrupted. Upon return from the signal handler,fcntl()shall return-1witherrnoset to[EINTR], and the lock operation shall not be done. ๐
Additional implementation-defined values for cmd may be defined in <fcntl.h>. Their names shall start with F_. iykyk.
When a shared lock is set on a segment of a file, other processes shall be able to 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 shall fail if the file descriptor was not opened with read access. ๐ซถ
An exclusive lock shall prevent 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 shall fail if the file descriptor was not opened with write access. no cap.
The structure flock describes the type (l_type), starting offset (l_whence), relative offset (l_start), size (l_len), and process ID (l_pid) of the segment of the file to be affected. ๐ธ
The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END, to indicate that the relative offset l_start bytes shall 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. The value of l_len may be negative (where the definition of off_t permits negative values of l_len). The l_pid field is only used with F_GETLK to return the process ID of the process holding a blocking lock. After a successful F_GETLK request, when a blocking lock is found, the values returned in the flock structure shall be as follows:
l_typeโ Type of blocking lock found.l_whenceโSEEK_SET.l_startโ Start of the blocking lock.l_lenโ Length of the blocking lock.l_pidโ Process ID of the process that holds the blocking lock.
If the command is F_SETLKW and the process must wait for another process to release a lock, then the range of bytes to be locked shall be determined before the fcntl() function blocks. If the file size or file descriptor seek offset change while fcntl() is blocked, this shall not affect the range of bytes locked. โญ
If l_len is positive, the area affected shall start at l_start and end at l_start+l_len-1. If l_len is negative, the area affected shall start at l_start+l_len and end at l_start-1. Locks may start and extend beyond the current end of a file, but shall not extend before the beginning of the file. A lock shall be set to extend to the largest possible value of the file offset for that file by setting l_len to 0. If such a lock also has l_start set to 0 and l_whence is set to SEEK_SET, the whole file shall be locked. ๐
There shall be at most one type of lock set for each byte in the file, bestie. That's the law. ๐
Before a successful return from an F_SETLK or an F_SETLKW request, when the calling process already has locks on bytes in the region the request is asking about, the previous lock type for each byte in that specified region gets replaced by the new lock type. No leftovers, no haunted old locks. And like we said up above with the shared and exclusive lock descriptions โ an F_SETLK or an F_SETLKW request (respectively) shall fail or block when another process already has locks on bytes in the specified region and the type of any of those locks conflicts with the type you asked for. It's giving "sorry babe, taken". ๐
All locks associated with a file for a given process shall be removed when a file descriptor for that file is closed by that process, or when the process holding that file descriptor terminates. And listen โ locks are NOT inherited by a child process. The kids get nothing. ๐ญ
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. Mutual "you first" energy, and nobody moves. If the system detects that sleeping until a locked region is unlocked would cause a deadlock, fcntl() shall fail with an [EDEADLK] error. ๐
An unlock (F_UNLCK) request in which l_len is non-zero and the offset of the last byte of the requested segment is the maximum value for an object of type off_t, when the process has an existing lock in which l_len is 0 and which includes the last byte of the requested segment, shall be treated as a request to unlock from the start of the requested segment with an l_len equal to 0. Otherwise, an unlock (F_UNLCK) request shall attempt to unlock only the requested segment. Specific. Precise. Iconic.
When the file descriptor fildes refers to a shared memory object, the behavior of fcntl() shall be the same as for a regular file except the effect of the following values for the argument cmd shall be unspecified: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW. So like... good luck, it's vibes only. ๐ฆ
If fildes refers to a typed memory object, the result of the fcntl() function is unspecified. Full mystery mode. ๐ฎ
๐ RETURN VALUE ๐
Upon successful completion, the value returned shall depend on cmd, and the way it depends is literally this:
F_DUPFDโ a new file descriptor. Fresh fd, who dis. โจF_DUPFD_CLOEXECโ a new file descriptor. Same deal, now with close-on-exec flavor. ๐F_GETFDโ the value of flags defined in<fcntl.h>. The return value shall not be negative. We don't do negative here.F_SETFDโ a value other than-1.F_GETFLโ the value of file status flags and access modes. The return value is not negative.F_SETFLโ a value other than-1.F_GETLKโ a value other than-1.F_SETLKโ a value other than-1.F_SETLKWโ a value other than-1.F_GETOWNโ the value of the socket owner process or process group; this will not be-1.F_SETOWNโ a value other than-1.
Otherwise, -1 shall be returned and errno set to indicate the error. Otherwise is the villain arc. ๐ญ
๐จ ERRORS ๐จ
The fcntl() function shall fail if:
EACCESorEAGAINโ thecmdargument isF_SETLK; the type of lock (l_type) is a shared (F_RDLCK) or exclusive (F_WRLCK) lock 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. Somebody got there first. ๐EBADFโ thefildesargument is not a valid open file descriptor, or the argumentcmdisF_SETLKorF_SETLKW, the type of lock,l_type, is a shared lock (F_RDLCK), andfildesis not a valid file descriptor open for reading, or the type of lock,l_type, is an exclusive lock (F_WRLCK), andfildesis not a valid file descriptor open for writing. Right fd, wrong permissions, tragic. ๐EINTRโ thecmdargument isF_SETLKWand the function was interrupted by a signal. Jump scare.EINVALโ thecmdargument is invalid, or thecmdargument isF_DUPFDorF_DUPFD_CLOEXECandargis negative or greater than or equal to{OPEN_MAX}, or thecmdargument isF_GETLK,F_SETLK, orF_SETLKWand the data pointed to byargis not valid, orfildesrefers to a file that does not support locking. So many ways to be invalid, honestly impressive. ๐EMFILEโ the argumentcmdisF_DUPFDorF_DUPFD_CLOEXECand all file descriptors available to the process are currently open, or no file descriptors greater than or equal toargare available. The fd budget is spent. ๐ญENOLCKโ the argumentcmdisF_SETLKorF_SETLKWand satisfying the lock or unlock request would result in the number of locked regions in the system exceeding a system-imposed limit. Too many locks, the system said no more. ๐ฅEOVERFLOWโ one of the values to be returned cannot be represented correctly.EOVERFLOWโ thecmdargument isF_GETLK,F_SETLK, orF_SETLKWand the smallest or, ifl_lenis non-zero, the largest offset of any byte in the requested segment cannot be represented correctly in an object of typeoff_t. Yes bestie,EOVERFLOWreally is listed twice, that's canon, don't @ me. โจESRCHโ thecmdargument isF_SETOWNand no process or process group can be found corresponding to that specified byarg. Ghosted. ๐ป
The fcntl() function may fail if:
EDEADLKโ thecmdargument isF_SETLKW, the lock is blocked by a lock from another process, and putting the calling process to sleep to wait for that lock to become free would cause a deadlock. Nobody moves, forever. ๐EINVALโ thecmdargument isF_SETOWNand the value of the argument is not valid as a process or process group identifier.EPERMโ thecmdargument isF_SETOWNand the calling process does not have permission to send aSIGURGsignal to any process specified byarg. Permission check said absolutely not. ๐ซ
The following sections are informative. Which is code for "chill, this part is just showing you the moves". ๐บ
โจ EXAMPLES โจ
๐ Locking and Unlocking a File ๐
The following example demonstrates how to place a lock on bytes 100 to 109 of a file and then later remove it. F_SETLK is used to perform a non-blocking lock request so that the process does not have to wait if an incompatible lock is held by another process; instead the process can take some other action. It's giving "not gonna sit here waiting, I have a life". ๐
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int fd;
struct flock fl;
fd = open("testfile", O_RDWR);
if (fd == -1)
/* Handle error */;
/* Make a non-blocking request to place a write lock
on bytes 100-109 of testfile */
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1) {
if (errno == EACCES || errno == EAGAIN) {
printf("Already locked by another process\n");
/* We cannot get the lock at the moment */
} else {
/* Handle unexpected error */;
}
} else { /* Lock was granted... */
/* Perform I/O on bytes 100 to 109 of file */
/* Unlock the locked bytes */
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1)
/* Handle error */;
}
exit(EXIT_SUCCESS);
} /* main */
๐ Setting the Close-on-Exec Flag ๐
The following example demonstrates how to set the close-on-exec flag for the file descriptor fd. Read it, modify it, write it back โ that's the whole ritual. ๐ง
#include <unistd.h>
#include <fcntl.h>
...
int flags;
flags = fcntl(fd, F_GETFD);
if (flags == -1)
/* Handle error */;
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1)
/* Handle error */;"
ngl bestie, that trailing " is literally in the source text. I am not touching it. It's part of the lore now. ๐ซถ
๐ธ APPLICATION USAGE ๐ธ
The arg values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent flag values to allow for future growth. Applications using these functions should do a read-modify-write operation on them, rather than assuming that only the values defined by this volume of POSIX.1โ2017 are valid. It is a common error to forget this, particularly in the case of F_SETFD. So don't be that girl โ read it, change it, write it back. Periodt. ๐
Some implementations set additional file status flags to advise the application of default behavior, even though the application did not request these flags. Surprise flags! Not yours, but here they are. ๐ฆ
On systems which do not perform permission checks at the time of an fcntl() call with F_SETOWN, if the permission checks performed at the time the signal is sent disallow sending the signal to any process, the process that called fcntl() has no way of discovering that this has happened. Silent failure, the worst genre. ๐ญ
A call to kill() with signal 0 can be used as a prior check of permissions, although this is no guarantee that permission will be granted at the time a signal is sent, since the target process(es) could change user IDs or privileges in the meantime. Check now, wrong later โ classic. ๐
๐ญ RATIONALE (the lore dump, bestie) ๐ญ
Okay so first thing, that ellipsis in the SYNOPSIS? Not a typo, not me being mysterious on purpose. It's literally the syntax the ISO C standard specifies for a variable number of arguments. It's there because System V uses pointers for the implementation of file locking functions. Iconic of them honestly.
This volume of POSIX.1โ2017 permits concurrent read and write access to file data using the fcntl() function. That is a whole change from the 1984 /usr/group standard and early proposals, no cap. And the tea is: without concurrency controls, this feature may not be fully utilized without occasional loss of data. Occasional loss of data. Bestie. We do not love that.
So how does the data loss happen? Several ways, let me spill:
- One case is when several processes try to update the same record, without sequencing controls. Several updates may occur in parallel and the last writer "wins". Last writer wins is not a vibe, it's a hazard.
- Another case is a bit-tree or other internal list-based database that is undergoing reorganization. Without exclusive use to the tree segment by the updating process, other reading processes chance getting lost in the database when the index blocks are split, condensed, inserted, or deleted. Genuinely lost. In the database. ๐ซ
And while fcntl() is useful for many applications, it is not intended to be overly general, and it does not handle the bit-tree example well. It said "not my genre" and honestly, fair.
This facility is only required for regular files, because it is not appropriate for many devices such as terminals and network connections.
Since fcntl() works with "any file descriptor associated with that file, however it is obtained", the file descriptor may have been inherited through a fork() or exec operation, and thus may affect a file that another process also has open. Plot twist: the fd has lore you don't know about.
The use of the open file description to identify what to lock requires extra calls and presents problems if several processes are sharing an open file description, but there are too many implementations of the existing mechanism for this volume of POSIX.1โ2017 to use different specifications. They're locked in. Pun absolutely intended. ๐
Another consequence of this model, and this one matters a LOT: closing any file descriptor for a given file (whether or not it is the same open file description that created the lock) causes the locks on that file to be relinquished for that process. Equivalently, any close for any file/process pair relinquishes the locks owned on that file for that process.
โ ๏ธ But note: while an open file description may be shared throughfork(), locks are not inherited throughfork(). Yet locks may be inherited through one of theexecfunctions. Yes, this is the exact kind of chaotic energy that ruins your afternoon. Write it down. ๐
The identification of a machine in a network environment is outside the scope of this volume of POSIX.1โ2017. Thus, an l_sysid member, such as found in System V, is not included in the locking structure. Not in the group chat, not in the struct.
Changing of lock types can result in a previously locked region being split into smaller regions. Splitting. Regions. As a treat.
Mandatory locking was a major feature of the 1984 /usr/group standard. And now, the whole discussion:
For advisory file record locking to be effective, all processes that have access to a file must cooperate and use the advisory mechanism before doing I/O on the file. Enforcement-mode record locking is important when it cannot be assumed that all processes are cooperating. Example, because this one is so real: if one user uses an editor to update a file at the same time that a second user executes another process that updates the same file, and if only one of the two processes is using advisory locking, the processes are not cooperating. Enforcement-mode record locking would protect against accidental collisions.
Secondly, advisory record locking requires a process using locking to bracket each I/O operation with lock (or test) and unlock operations. With enforcement-mode file and record locking, a process can lock the file once and unlock when all I/O operations have been completed. Enforcement-mode record locking provides a base that can be enhanced โ for example, with sharable locks. That is, the mechanism could be enhanced to allow a process to lock a file so other processes could read it, but none of them could write it. Dream scenario, honestly.
Mandatory locks were omitted for several reasons, and each one ate:
- Mandatory lock setting was done by multiplexing the
set-group-IDbit in most implementations. This was confusing, at best. At best!! - The relationship to file truncation as supported in 4.2 BSD was not well specified.
- Any publicly readable file could be locked by anyone. Many historical implementations keep the password database in a publicly readable file. A malicious user could thus prohibit logins. Another possibility would be to hold open a long-distance telephone line. ๐
- Some demand-paged historical implementations offer memory mapped files, and enforcement cannot be done on that type of file.
And last one, the practical tip of the section: since sleeping on a region is interrupted with any signal, alarm() may be used to provide a timeout facility in applications requiring it. This is useful in deadlock detection. And since implementation of full deadlock detection is not always feasible, the [EDEADLK] error was made optional. Not mandatory. Optional. Like plans.
๐ฎ FUTURE DIRECTIONS ๐ฎ
None. Nothing. The future is empty, bestie, and honestly that's a vibe. ๐
๐ SEE ALSO ๐
alarm()close()execkill()open()sigaction()
The Base Definitions volume of POSIX.1โ2017, <fcntl.h>, <signal.h>
๐ COPYRIGHT ๐
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
And that's the whole page, bestie. ๐ This masterpiece was brought to you by IEEE and The Open Group, dated 2017, filed forever under FCNTL(3P). Go forth and lock responsibly. ๐ฆ๐
โจ
๐ฆ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 ยท custom
- alpine 3.23: man-pages-posix 2017a-r0 ยท custom
- alpine 3.24: man-pages-posix 2017a-r0 ยท custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 ยท SUSE-IEEE
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms