OPEN(3P)
๐ซถ PROLOG ๐ซถ
okay so bestie, this is OPEN(3P) from the POSIX Programmer's Manual โ yes, the whole open / openat situation. This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (so pls consult the corresponding Linux manual page for details on Linux behavior), or the interface may not be implemented on Linux at all. ๐
๐ NAME ๐
open, openat โ open file
โจ SYNOPSIS โจ
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *path, int oflag, ...);
int openat(int fd, const char *path, int oflag, ...);
๐ DESCRIPTION ๐
okay so open() does the whole "establish the connection between a file and a file descriptor" thing. It creates an open file description that refers to a file, and a file descriptor that refers to that open file description. Other I/O functions use that fd to refer to the file. The path argument points to a pathname naming the file.
open() returns a file descriptor for the named file, allocated as described in Section 2.14, File Descriptor Allocation. The open file description is brand new, so the fd shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new fd shall be cleared unless O_CLOEXEC is set in oflag.
The file offset that marks current position within the file shall be set to the beginning of the file.
The file status flags and file access modes of the open file description shall be set according to oflag.
Values for oflag are made by bitwise-inclusive OR of flags from the list below, defined in <fcntl.h>. Applications shall specify exactly one of the first five values (the file access modes) in oflag:
O_EXECโ open for execute only (non-directory files). If you apply this to a directory, the result is unspecified. ๐O_RDONLYโ open for reading only.O_RDWRโ open for reading and writing. If you apply this to a FIFO, the result is undefined. ๐O_SEARCHโ open directory for search only. If you apply this to a non-directory file, the result is unspecified. ๐O_WRONLYโ open for writing only.
Any combination of the following may be used:
O_APPENDโ if set, the file offset shall be set to the end of the file prior to each write.O_CLOEXECโ if set, theFD_CLOEXECflag for the new file descriptor shall be set.O_CREATโ if the file exists, this flag has no effect except as noted underO_EXCLbelow. Otherwise, ifO_DIRECTORYis not set, the file shall be created as a regular file; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see<sys/stat.h>) of the file mode shall be set to the value of the argument following theoflagargument, taken as typemode_t, modified like this: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. So all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The argument following theoflagargument does not affect whether the file is open for reading, writing, or both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.O_DIRECTORYโ ifpathresolves to a non-directory file, fail and seterrnoto[ENOTDIR].O_DSYNCโ write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.O_EXCLโ ifO_CREATandO_EXCLare set,open()shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executingopen()naming the same filename in the same directory withO_EXCLandO_CREATset. IfO_EXCLandO_CREATare set, andpathnames a symbolic link,open()shall fail and seterrnoto[EEXIST], regardless of the contents of the symbolic link. IfO_EXCLis set andO_CREATis not set, the result is undefined. ๐O_NOCTTYโ if set andpathidentifies a terminal device,open()shall not cause the terminal device to become the controlling terminal for the process. Ifpathdoes not identify a terminal device,O_NOCTTYshall be ignored.O_NOFOLLOWโ ifpathnames a symbolic link, fail and seterrnoto[ELOOP].O_NONBLOCKโ when opening a FIFO withO_RDONLYorO_WRONLYset:- If
O_NONBLOCKis set, anopen()for reading-only shall return without delay. Anopen()for writing-only shall return an error if no process currently has the file open for reading. - If
O_NONBLOCKis clear, anopen()for reading-only shall block the calling thread until a thread opens the file for writing. Anopen()for writing-only shall block the calling thread until a thread opens the file for reading. When opening a block special or character special file that supports non-blocking opens: - If
O_NONBLOCKis set, theopen()function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific. - If
O_NONBLOCKis clear, theopen()function shall block the calling thread until the device is ready or available before returning. Otherwise, theO_NONBLOCKflag shall not cause an error, but it is unspecified whether the file status flags will include theO_NONBLOCKflag.
- If
O_RSYNCโ read I/O operations on the file descriptor shall complete at the same level of integrity as specified by theO_DSYNCandO_SYNCflags. If bothO_DSYNCandO_RSYNCare set inoflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If bothO_SYNCandO_RSYNCare set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.O_SYNCโ write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion. TheO_SYNCflag shall be supported for regular files, even if the Synchronized Input and Output option is not supported.O_TRUNCโ if the file exists and is a regular file, and the file is successfully openedO_RDWRorO_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of usingO_TRUNCwithout eitherO_RDWRorO_WRONLYis undefined. ๐O_TTY_INITโ ifpathidentifies a terminal device other than a pseudo-terminal, the device is not already open in any process, and eitherO_TTY_INITis set inoflagorO_TTY_INIThas the value zero,open()shall set any non-standardtermiosstructure terminal parameters to a state that provides conforming behavior; see the Base Definitions volume of POSIX.1-2017, Section 11.2, Parameters that Can be Set. It is unspecified whetherO_TTY_INIThas any effect if the device is already open in any process. Ifpathidentifies the slave side of a pseudo-terminal that is not already open in any process,open()shall set any non-standardtermiosstructure terminal parameters to a state that provides conforming behavior, regardless of whetherO_TTY_INITis set. Ifpathdoes not identify a terminal device,O_TTY_INITshall be ignored.
If O_CREAT and O_DIRECTORY are set and the requested access mode is neither O_WRONLY nor O_RDWR, the result is unspecified.
If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the last data access, last data modification, and last file status change timestamps of the file and the last data modification and last file status change timestamps of the parent directory.
If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the last data modification and last file status change timestamps of the file.
If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set.
If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific.
The application shall ensure that it specifies the O_TTY_INIT flag on the first open of a terminal device since system boot or since the device was closed by the process that last had it open. The application need not specify the O_TTY_INIT flag when opening pseudo-terminals. If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side.
The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description. That's the ceiling, bestie โ the biggest offset that lil file description can even hold. โจ
openat() โ the glow-up version of open() ๐
The openat() function shall be equivalent to the open() function except in the case where path specifies a relative path. In this case the file to be opened is determined relative to the directory associated with the file descriptor fd instead of the current working directory.
If the access mode of the open file description associated with the file descriptor is not O_SEARCH, the function shall check whether directory searches are permitted using the current permissions of the directory underlying the file descriptor. If the access mode is O_SEARCH, the function shall not perform the check. (no vibe check needed, we already know โจ)
The oflag parameter and the optional fourth parameter correspond exactly to the parameters of open(). fr fr, same params, same energy.
If openat() is passed the special value AT_FDCWD in the fd parameter, the current working directory shall be used and the behavior shall be identical to a call to open(). ๐ซถ
๐ธ RETURN VALUE ๐ธ
Upon successful completion, these functions shall open the file and return a non-negative integer representing the file descriptor. ๐
Otherwise, these functions shall return -1 and set errno to indicate the error. If -1 is returned, no files shall be created or modified. Not a single file. Nothing. Zero. Nada. ๐
๐ ERRORS ๐
These functions shall fail if:
EACCESโ Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, orO_TRUNCis specified and write permission is denied.EEXISTโO_CREATandO_EXCLare set, and the named file exists. (it's already there, bestie, we're not doing duplicates โ)EINTRโ A signal was caught duringopen().EINVALโ The implementation does not support synchronized I/O for this file.EIOโ The path argument names a STREAMS file and a hangup or error occurred during theopen().EISDIRโ The named file is a directory and oflag includesO_WRONLYorO_RDWR, or includesO_CREATwithoutO_DIRECTORY.ELOOPโ A loop exists in symbolic links encountered during resolution of the path argument, orO_NOFOLLOWwas specified and the path argument names a symbolic link. symlink loop arc, iconic but illegal โจEMFILEโ All file descriptors available to the process are currently open.ENAMETOOLONGโ The length of a component of a pathname is longer than{NAME_MAX}.ENFILEโ The maximum allowable number of files is currently open in the system.ENOENTโO_CREATis not set and a component of path does not name an existing file, orO_CREATis set and a component of the path prefix of path does not name an existing file, or path points to an empty string.ENOENTorENOTDIRโO_CREATis set, and the path argument contains at least one non-<slash>character and ends with one or more trailing<slash>characters. If path without the trailing<slash>characters would name an existing file, an[ENOENT]error shall not occur. (so don't come for it unless it actually doesn't exist ๐)ENOSRโ The path argument names a STREAMS-based file and the system is unable to allocate a STREAM.ENOSPCโ The directory or file system that would contain the new file cannot be expanded, the file does not exist, andO_CREATis specified.ENOTDIRโ A component of the path prefix names an existing file that is neither a directory nor a symbolic link to a directory; orO_CREATandO_EXCLare not specified, the path argument contains at least one non-<slash>character and ends with one or more trailing<slash>characters, and the last pathname component names an existing file that is neither a directory nor a symbolic link to a directory; orO_DIRECTORYwas specified and the path argument resolves to a non-directory file.ENXIOโO_NONBLOCKis set, the named file is a FIFO,O_WRONLYis set, and no process has the file open for reading. (nobody's on the other end of the line, babe ๐ญ)ENXIOโ The named file is a character special or block special file, and the device associated with this special file does not exist.EOVERFLOWโ The named file is a regular file and the size of the file cannot be represented correctly in an object of typeoff_t. too big for the vibe, it's giving overflow โจEROFSโ The named file resides on a read-only file system and eitherO_WRONLY,O_RDWR,O_CREAT(if the file does not exist), orO_TRUNCis set in the oflag argument.
openat() shall fail if: ๐ฆ
EACCESโ The access mode of the open file description associated with fd is notO_SEARCHand the permissions of the directory underlying fd do not permit directory searches.EBADFโ The path argument does not specify an absolute path and the fd argument is neitherAT_FDCWDnor a valid file descriptor open for reading or searching.ENOTDIRโ The path argument is not an absolute path and fd is a file descriptor associated with a non-directory file.
These functions may fail if: ๐ง
EAGAINโ The path argument names the slave side of a pseudo-terminal device that is locked.EINVALโ The value of the oflag argument is not valid.ELOOPโ More than{SYMLOOP_MAX}symbolic links were encountered during resolution of the path argument.ENAMETOOLONGโ The length of a pathname exceeds{PATH_MAX}, or pathname resolution of a symbolic link produced an intermediate result with a length that exceeds{PATH_MAX}.ENOMEMโ The path argument names a STREAMS file and the system is unable to allocate resources.EOPNOTSUPPโ The path argument names a socket. (a socket is not a file, we do not open it, periodt ๐ )ETXTBSYโ The file is a pure procedure (shared text) file that is being executed and oflag isO_WRONLYorO_RDWR.
The following sections are informative. (translation: this is the fun stuff, not the contract โจ)
๐ EXAMPLES ๐
๐ธ Opening a File for Writing by the Owner ๐ธ
The following example opens the file /tmp/file, either by creating it (if it does not already exist), or by truncating its length to 0 (if it does exist). In the former case, if the call creates a new file, the access permission bits in the file mode of the file are set to permit reading and writing by the owner, and to permit reading only by group members and others. owner gets full main character energy, everyone else just gets to look ๐
If the call to open() is successful, the file is opened for writing.
#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *pathname = "/tmp/file";
...
fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
...
๐ฆ Opening a File Using an Existence Check ๐ฆ
The following example uses the open() function to try to create the LOCKFILE file and open it for writing. Since the open() function specifies the O_EXCL flag, the call fails if the file already exists. In that case, the program assumes that someone else is updating the password file and exits. (it's taken bestie, we're leaving ๐ช)
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
...
int pfd; /* Integer for file descriptor returned by open() call. */
...
if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
exit(1);
}
...
๐ Opening a File for Writing ๐
The following example opens a file for writing, creating the file if it does not already exist. If the file does exist, the system truncates the file to zero bytes. poof. gone. ๐
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
...
int pfd;
char pathname[PATH_MAX+1];
...
if ((pfd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
...
โจ APPLICATION USAGE โจ
okay listen up, this part is important ๐
POSIX.1โ2008 does not require that terminal parameters be automatically set to any state on first open, nor that they be reset after the last close. It is possible for a non-conforming application to leave a terminal device in a state where the next process to use that device finds it in a non-conforming state, but has no way of determining this. (mystery terminal state = horror movie energy ๐ญ)
To ensure that the device is set to a conforming initial state, applications which perform a first open of a terminal (other than a pseudo-terminal) should do so using the O_TTY_INIT flag to set the parameters associated with the terminal to a conforming state. do this, bestie, your future self will thank you ๐ซถ
Except as specified in this volume of POSIX.1โ2017, the flags allowed in oflag are not mutually-exclusive and any number of them may be used simultaneously. (mix and match, it's a vibe โจ)
Not all combinations of flags make sense. For example, using O_SEARCH | O_CREAT will successfully open a pre-existing directory for searching, but if there is no existing file by that name, then it is unspecified whether a regular file will be created.
Likewise, if a non-directory file descriptor is successfully returned, it is unspecified whether that descriptor will have execute permissions as if by O_EXEC โ and note that it is unspecified whether O_EXEC and O_SEARCH have the same value. iykyk ๐
โจ RATIONALE โจ (aka the why behind all of this, bestie)
Okay so, some implementations out there will let you open FIFOs with O_RDWR. But FIFOs could legitimately be implemented in other ways, and since you can just use two file descriptors to get the exact same effect, this possibility is left as undefined. ๐ซ
Wanna know about the group of a newly created file? Go check out getgroups() for that.
Using open() to create a regular file is preferable to using creat(), because creat() is redundant and only exists for historical reasons. It's giving legacy code, honestly. ๐
The use of the O_TRUNC flag on FIFOs and directories (pipes cannot be open()-ed, sorry babe) must be permissible without unexpected side-effects โ for example, creat() on a FIFO must not remove data. And since terminal special files might have type-ahead data stored in the buffer, O_TRUNC should not affect their content, especially if a program that normally opens a regular file ends up opening the current controlling terminal instead. Other file types, particularly implementation-defined ones, are left implementation-defined. iykyk. ๐คทโโ๏ธ
POSIX.1โ2008 permits [EACCES] to be returned for conditions other than the ones explicitly listed. Sneaky but legal.
The O_NOCTTY flag was added so applications can avoid accidentally acquiring a controlling terminal as a side-effect of opening a terminal file. This volume of POSIX.1โ2017 doesn't specify how a controlling terminal gets acquired, but it does allow an implementation to provide that on open() if the O_NOCTTY flag is not set and the other conditions specified in the Base Definitions volume of POSIX.1โ2017, Chapter 11, General Terminal Interface, are met. ๐
In historical implementations the value of O_RDONLY is zero. Because of that, it is not possible to detect the presence of O_RDONLY and another option. Future implementations should encode O_RDONLY and O_WRONLY as bit flags so that:
O_RDONLY | O_WRONLY == O_RDWR
O_EXEC and O_SEARCH are specified as two of the five file access modes. Since O_EXEC does not apply to directories, and O_SEARCH only applies to directories, their values need not be distinct. And since O_RDONLY has historically had the value zero, implementations are not able to distinguish between O_SEARCH and O_SEARCH | O_RDONLY โ and similarly for O_EXEC. Messy? A little. Iconic? Also yes. ๐
In general, the open() function follows the symbolic link if path names a symbolic link. However โ and this is the plot twist โ open(), when called with O_CREAT and O_EXCL, is required to fail with [EEXIST] if path names an existing symbolic link, even if that symbolic link refers to a nonexistent file. Why? So privileged applications can create a new file in a known location without the possibility that a symbolic link might cause the file to be created somewhere else entirely. ๐ฏ
Like, picture this: a privileged application that must create a file with a predictable name in a user-writable directory, such as the user's home directory, could be compromised if the user creates a symbolic link with that name that refers to a nonexistent file in a system directory. And if the user can influence the contents of a file, they could compromise the system by creating a new system configuration or spool file that the system would then interpret. ๐ญ The test for a symbolic link which refers to a nonexisting file must be atomic with the creation of a new file. No take-backs, no race conditions, periodt.
On top of that, open() refuses to open non-directories if the O_DIRECTORY flag is set. This avoids race conditions where a user might compromise the system by substituting a hard link to a sensitive file (e.g., a device or a FIFO) while a privileged application is running โ situations where opening a file even for read access might have undesirable side-effects. ๐
Also, open() does not follow symbolic links if the O_NOFOLLOW flag is set. Same energy: it avoids race conditions where a user might compromise the system by substituting a symbolic link to a sensitive file (e.g., a device) while a privileged application is running, where opening a file even for read access might have undesirable side-effects. ๐ฅ
The POSIX.1โ1990 standard required that the group ID of a newly created file be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151โ2 required that implementations provide a way to have the group ID be set to the group ID of the containing directory, but did not prohibit implementations from also supporting a way to set the group ID to the effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If it matters, an application can use chown() to set the group ID after the file is created, or determine under what conditions the implementation will set the desired group ID. Bestie, just don't assume. ๐
โโ๏ธ
The whole point of the openat() function is to enable opening files in directories other than the current working directory without exposure to race conditions. Any part of the path of a file could be changed in parallel to a call to open(), which would result in unspecified behavior. But by opening a file descriptor for the target directory and using the openat() function, you can guarantee that the opened file is located relative to the desired directory. Slay. ๐ฆ
Some implementations use the openat() function for other purposes as well. In some cases, if the oflag parameter has the O_XATTR bit set, the returned file descriptor provides access to extended attributes. This functionality is not standardized here. Note it and move on. โญ
๐ฎ FUTURE DIRECTIONS ๐ฎ
None.
Like, literally nothing. The future is empty. The vibe is calm. ๐
๐ SEE ALSO ๐
chmod()close()creat()dirfd()dup()execfcntl()fdopendir()link()lseek()mkdtemp()mknod()read()symlink()umask()unlockpt()write()
And also: The Base Definitions volume of POSIX.1โ2017, Chapter 11, General Terminal Interface, <fcntl.h>, <sys_stat.h>, <sys_types.h>. Go read them, bestie, they're right there. ๐
ยฉ๏ธ 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 lil masterpiece comes courtesy of IEEE/The Open Group, stamped 2017, living under the name OPEN(3P). go forth and open() responsibly, mwah ๐โจ๐ซถ
๐ฆ 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