open, openat - open file
[OH]#include<sys/stat.h>
#include <fcntl.h>
int open(const char *path, intoflag, ...);
int openat(intfd, const char *path, intoflag, ...);
Theopen() function shall establish the connection between a file and a file descriptor. It shall create an open filedescription that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used byother I/O functions to refer to that file. Thepath argument points to a pathname naming the file.
Theopen() function shall return a file descriptor for the named file, allocated as described inFile Descriptor Allocation. The open file description is new, and therefore thefile descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with thenew file descriptor shall be cleared unless the O_CLOEXEC flag is set inoflag.
The file offset used to mark the 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 the value ofoflag.
Values foroflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in<fcntl.h>. Applications shall specify exactly one of the first five values (file accessmodes) below in the value ofoflag:
- O_EXEC
- Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.
- O_RDONLY
- Open for reading only.
- O_RDWR
- Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
- O_SEARCH
- Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.
- 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, the FD_CLOEXEC flag for the new file descriptor shall be set.
- O_CREAT
- If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, if O_DIRECTORY is not set the fileshall 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 ofthe 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 accesspermission bits (see<sys/stat.h>) of the file mode shall be set to thevalue of the argument following theoflag argument taken as typemode_t modified as follows: a bitwise AND isperformed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, allbits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the filepermission bits are set, the effect is unspecified. The argument following theoflag argument does not affect whether thefile is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the groupID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's groupID to the effective group ID of the calling process.
- O_DIRECTORY
- Ifpath resolves to a non-directory file, fail and seterrno to [ENOTDIR].
- O_DSYNC
- [SIO]
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.
- O_EXCL
- If O_CREAT and O_EXCL are set,open() shall fail if the file exists. The check for the existence of the file and thecreation of the file if it does not exist shall be atomic with respect to other threads executingopen() naming the samefilename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, andpath names a symbolic link,open() shall fail and seterrno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set andO_CREAT is not set, the result is undefined.
- O_NOCTTY
- If set andpath identifies a terminal device,open() shall not cause the terminal device to become thecontrolling terminal for the process. Ifpath does not identify a terminal device, O_NOCTTY shall be ignored.
- O_NOFOLLOW
- Ifpath names a symbolic link, fail and seterrno to [ELOOP].
- O_NONBLOCK
- When opening a FIFO with O_RDONLY or O_WRONLY set:
If O_NONBLOCK is set, anopen() for reading-only shall return without delay. Anopen() for writing-only shallreturn an error if no process currently has the file open for reading.
If O_NONBLOCK is clear, anopen() for reading-only shall block the calling thread until a thread opens the file forwriting. 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_NONBLOCK is 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_NONBLOCK is clear, theopen() function shall block the calling thread until the device is ready or available beforereturning.
Otherwise, the O_NONBLOCK flag shall not cause an error, but it is unspecified whether the file status flags will include theO_NONBLOCK flag.
- O_RSYNC
- [SIO]
Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNCflags. If both O_DSYNC and O_RSYNC are set inoflag, all I/O operations on the file descriptor shall complete as defined bysynchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptorshall complete as defined by synchronized I/O file integrity completion.
- O_SYNC
- [XSI|SIO]
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
[XSI]
The O_SYNC flag 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 opened O_RDWR or O_WRONLY, its length shall be truncatedto 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effecton other file types is implementation-defined. The result of using O_TRUNC without either O_RDWR or O_WRONLY is undefined.
- O_TTY_INIT
- Ifpath identifies a terminal device other than a pseudo-terminal, the device is not already open in any process, andeither O_TTY_INIT is set inoflag or O_TTY_INIT has the value zero,open() shall set any non-standardtermiosstructure terminal parameters to a state that provides conforming behavior; see XBDParameters that Can be Set. It is unspecified whether O_TTY_INIT has any effectif the device is already open in any process. Ifpath identifies the slave side of a pseudo-terminal that is not alreadyopen in any process,open() shall set any non-standardtermios structure terminal parameters to a state that providesconforming behavior, regardless of whether O_TTY_INIT is set. Ifpath does not identify a terminal device, O_TTY_INIT shallbe 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 thelast data access, last data modification, and last file status change timestamps of the file and the last data modification andlast 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 lastdata modification and last file status change timestamps of the file.
[SIO]
If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set.
[OB XSR]
Ifpath 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 affectsthe operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMSdrivers, 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 orsince the device was closed by the process that last had it open. The application need not specify the O_TTY_INIT flag when openingpseudo-terminals.[XSI]
Ifpath names the master side of a pseudo-terminal device, then it is unspecified whetheropen() locks the slave side so that it cannot be opened. Conforming applications shall callunlockpt() before opening the slave side.
The largest value that can be represented correctly in an object of typeoff_t shall be established as the offset maximumin the open file description.
Theopenat() function shall be equivalent to theopen() function except in the case wherepath specifies arelative path. In this case the file to be opened is determined relative to the directory associated with the file descriptorfd instead of the current working directory. If the access mode of the open file description associated with the filedescriptor is not O_SEARCH, the function shall check whether directory searches are permitted using the current permissions of thedirectory underlying the file descriptor. If the access mode is O_SEARCH, the function shall not perform the check.
Theoflag parameter and the optional fourth parameter correspond exactly to the parameters ofopen().
Ifopenat() is passed the special value AT_FDCWD in thefd parameter, the current working directory shall be usedand the behavior shall be identical to a call toopen().
Upon successful completion, these functions shall open the file and return a non-negative integer representing the filedescriptor. Otherwise, these functions shall return -1 and seterrno to indicate the error. If -1 is returned, no filesshall be created or modified.
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 byoflagare denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, orO_TRUNC is specified and write permission is denied.
- [EEXIST]
- O_CREAT and O_EXCL are set, and the named file exists.
- [EINTR]
- A signal was caught duringopen().
- [EINVAL]
- [SIO]
The implementation does not support synchronized I/O for this file.
- [EIO]
- [OB XSR]
Thepath argument names a STREAMS file and a hangup or error occurred during theopen().
- [EISDIR]
- The named file is a directory andoflag includes O_WRONLY or O_RDWR, or includes O_CREAT without O_DIRECTORY.
- [ELOOP]
- A loop exists in symbolic links encountered during resolution of thepath argument, or O_NOFOLLOW was specified and thepath argument names a symbolic link.
- [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_CREAT is not set and a component ofpath does not name an existing file, or O_CREAT is set and a component of the pathprefix ofpath does not name an existing file, orpath points to an empty string.
- [ENOENT] or [ENOTDIR]
- O_CREAT is set, and thepath argument contains at least one non- <slash> character and ends with one or more trailing<slash> characters. Ifpath without the trailing <slash> characters would name an existing file, an [ENOENT]error shall not occur.
- [ENOSR]
- [OB XSR]
Thepath 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, and O_CREAT isspecified.
- [ENOTDIR]
- A component of the path prefix names an existing file that is neither a directory nor a symbolic link to a directory; orO_CREAT and O_EXCL are not specified, thepath argument contains at least one non- <slash> character and ends with oneor more trailing <slash> characters, and the last pathname component names an existing file that is neither a directory nor asymbolic link to a directory; or O_DIRECTORY was specified and thepath argument resolves to a non-directory file.
- [ENXIO]
- O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
- [ENXIO]
- The named file is a character special or block special file, and the device associated with this special file does notexist.
- [EOVERFLOW]
- The named file is a regular file and the size of the file cannot be represented correctly in an object of typeoff_t.
- [EROFS]
- The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or O_TRUNCis set in theoflag argument.
Theopenat() function shall fail if:
- [EACCES]
- The access mode of the open file description associated withfd is not O_SEARCH and the permissions of the directoryunderlyingfd do not permit directory searches.
- [EBADF]
- Thepath argument does not specify an absolute path and thefd argument is neither AT_FDCWD nor a valid filedescriptor open for reading or searching.
- [ENOTDIR]
- Thepath argument is not an absolute path andfd is a file descriptor associated with a non-directory file.
These functions may fail if:
- [EAGAIN]
- [XSI]
Thepath argument names the slave side of a pseudo-terminal device that is locked.
- [EINVAL]
- The value of theoflag argument is not valid.
- [ELOOP]
- More than {SYMLOOP_MAX} symbolic links were encountered during resolution of thepath argument.
- [ENAMETOOLONG]
- The length of a pathname exceeds {PATH_MAX}, or pathname resolution of a symbolic link produced an intermediate result with alength that exceeds {PATH_MAX}.
- [ENOMEM]
- [OB XSR]
Thepath argument names a STREAMS file and the system is unable to allocate resources.
- [EOPNOTSUPP]
- Thepath argument names a socket.
- [ETXTBSY]
- The file is a pure procedure (shared text) file that is being executed andoflag is O_WRONLY or O_RDWR.
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 truncatingits 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 modeof the file are set to permit reading and writing by the owner, and to permit reading only by group members and others.
If the call toopen() 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 theopen() function to try to create theLOCKFILE file and open it for writing. Sincetheopen() function specifies the O_EXCL flag, the call fails if the file already exists. In that case, the program assumesthat someone else is updating the password file and exits.
#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, thesystem truncates the file to zero bytes.
#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);}...
POSIX.1-2017 does not require that terminal parameters be automatically set to any state on first open, nor that they be resetafter the last close. It is possible for a non-conforming application to leave a terminal device in a state where the next processto use that device finds it in a non-conforming state, but has no way of determining this. To ensure that the device is set to aconforming initial state, applications which perform a first open of a terminal (other than a pseudo-terminal) should do so usingthe O_TTY_INIT flag to set the parameters associated with the terminal to a conforming state.
Except as specified in this volume of POSIX.1-2017, the flags allowed inoflag are not mutually-exclusive and any numberof them may be used simultaneously. Not all combinations of flags make sense. For example, using O_SEARCH | O_CREAT willsuccessfully open a pre-existing directory for searching, but if there is no existing file by that name, then it is unspecifiedwhether a regular file will be created. Likewise, if a non-directory file descriptor is successfully returned, it is unspecifiedwhether that descriptor will have execute permissions as if by O_EXEC (note that it is unspecified whether O_EXEC and O_SEARCH havethe same value).
Some implementations permit opening FIFOs with O_RDWR. Since FIFOs could be implemented in other ways, and since two filedescriptors can be used to the same effect, this possibility is left as undefined.
Seegetgroups about the group of a newly created file.
The use ofopen() to create a regular file is preferable to the use ofcreat(), because the latter is redundant and included only for historical reasons.
The use of the O_TRUNC flag on FIFOs and directories (pipes cannot beopen()-ed) must be permissible without unexpectedside-effects (for example,creat() on a FIFO must not remove data). Since terminalspecial files might have type-ahead data stored in the buffer, O_TRUNC should not affect their content, particularly if a programthat normally opens a regular file should open the current controlling terminal instead. Other file types, particularlyimplementation-defined ones, are left implementation-defined.
POSIX.1-2017 permits [EACCES] to be returned for conditions other than those explicitly listed.
The O_NOCTTY flag was added to allow applications to avoid unintentionally acquiring a controlling terminal as a side-effect ofopening a terminal file. This volume of POSIX.1-2017 does not specify how a controlling terminal is acquired, but it allows animplementation to provide this onopen() if the O_NOCTTY flag is not set and other conditions specified in XBDGeneral 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 ofO_RDONLY and another option. Future implementations should encode O_RDONLY and O_WRONLY as bit flags so that:
O_RDONLY | O_WRONLY == O_RDWRO_EXEC and O_SEARCH are specified as two of the five file access modes. Since O_EXEC does not apply to directories, and O_SEARCHonly applies to directories, their values need not be distinct. Since O_RDONLY has historically had the value zero, implementationsare not able to distinguish between O_SEARCH and O_SEARCH | O_RDONLY, and similarly for O_EXEC.
In general, theopen() function follows the symbolic link ifpath names a symbolic link. However, theopen() function, when called with O_CREAT and O_EXCL, is required to fail with [EEXIST] ifpath names an existingsymbolic link, even if the symbolic link refers to a nonexistent file. This behavior is required so that privileged applicationscan create a new file in a known location without the possibility that a symbolic link might cause the file to be created in adifferent location.
For example, a privileged application that must create a file with a predictable name in a user-writable directory, such as theuser's home directory, could be compromised if the user creates a symbolic link with that name that refers to a nonexistent file ina system directory. If the user can influence the contents of a file, the user could compromise the system by creating a new systemconfiguration or spool file that would then be interpreted by the system. The test for a symbolic link which refers to anonexisting file must be atomic with the creation of a new file.
In addition, theopen() function refuses to open non-directories if the O_DIRECTORY flag is set. This avoids raceconditions whereby 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, where opening a file even for read access might have undesirable side-effects.
In addition, theopen() function does not follow symbolic links if the O_NOFOLLOW flag is set. This avoids raceconditions whereby a user might compromise the system by substituting a symbolic link to a sensitive file (e.g., a device) while aprivileged 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 orto the effective group ID of the creating process. FIPS 151-2 required that implementations provide a way to have the group ID beset to the group ID of the containing directory, but did not prohibit implementations also supporting a way to set the group ID tothe effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If itmatters, an application can usechown() to set the group ID after the file is created,or determine under what conditions the implementation will set the desired group ID.
The purpose of theopenat() function is to enable opening files in directories other than the current working directorywithout exposure to race conditions. Any part of the path of a file could be changed in parallel to a call toopen(),resulting in unspecified behavior. By opening a file descriptor for the target directory and using theopenat() function itcan be guaranteed that the opened file is located relative to the desired directory. Some implementations use theopenat()function for other purposes as well. In some cases, if theoflag parameter has the O_XATTR bit set, the returned filedescriptor provides access to extended attributes. This functionality is not standardized here.
None.
chmod,close,creat,dirfd,dup,exec,fcntl,fdopendir,link,lseek,mkdtemp,mknod,read,symlink,umask,unlockpt,write
XBDGeneral Terminal Interface,<fcntl.h>,<sys/stat.h>,<sys/types.h>
First released in Issue 1. Derived from Issue 1 of the SVID.
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX Threads Extension.
Large File Summit extensions are added.
In the SYNOPSIS, the optional include of the<sys/types.h> header isremoved.
The following new requirements on POSIX implementations derive from alignment with the Single UNIX Specification:
The requirement to include<sys/types.h> has been removed. Although<sys/types.h> was required for conforming implementations of previous POSIXspecifications, it was not required for UNIX applications.
In the DESCRIPTION, O_CREAT is amended to state that the group ID of the file is set to the group ID of the file's parentdirectory or to the effective group ID of the process. This is a FIPS requirement.
In the DESCRIPTION, text is added to indicate setting of the offset maximum in the open file description. This change is tosupport large files.
In the ERRORS section, the [EOVERFLOW] condition is added. This change is to support large files.
The [ENXIO] mandatory error condition is added.
The [EINVAL], [ENAMETOOLONG], and [ETXTBSY] optional error conditions are added.
The DESCRIPTION and ERRORS sections are updated so that items related to the optional XSI STREAMS Option Group are marked.
The following changes were made to align with the IEEE P1003.1a draft standard:
An explanation is added of the effect of the O_CREAT and O_EXCL flags when the path refers to a symbolic link.
The [ELOOP] optional error condition is added.
The normative text is updated to avoid use of the term "must" for application requirements.
The DESCRIPTION of O_EXCL is updated in response to IEEE PASC Interpretation 1003.1c #48.
Austin Group Interpretations 1003.1-2001 #113 and #143 are applied.
Austin Group Interpretation 1003.1-2001 #144 is applied, adding the O_TTY_INIT flag.
Austin Group Interpretation 1003.1-2001 #171 is applied, adding support to set the FD_CLOEXEC flag atomically atopen(),and adding the F_DUPFD_CLOEXEC flag.
SD5-XBD-ERN-4 is applied, changing the definition of the [EMFILE] error.
This page is revised and theopenat() function is added from The Open Group Technical Standard, 2006, Extended API SetPart 2.
Functionality relating to the XSI STREAMS option is marked obsolescent.
Changes are made related to support for finegrained timestamps.
Changes are made to allow a directory to be opened for searching.
POSIX.1-2008, Technical Corrigendum 1, XSH/TC1-2008/0418 [292], XSH/TC1-2008/0419 [141], XSH/TC1-2008/0420 [461],XSH/TC1-2008/0421 [390], XSH/TC1-2008/0422 [146], XSH/TC1-2008/0423 [324], XSH/TC1-2008/0424 [292], XSH/TC1-2008/0425 [278],XSH/TC1-2008/0426 [278], XSH/TC1-2008/0427 [291], and XSH/TC1-2008/0428 [307] are applied.
POSIX.1-2008, Technical Corrigendum 2, XSH/TC2-2008/0235 [873], XSH/TC2-2008/0236 [835], XSH/TC2-2008/0237 [847],XSH/TC2-2008/0238 [817], XSH/TC2-2008/0239 [835], XSH/TC2-2008/0240 [847], XSH/TC2-2008/0241 [822], XSH/TC2-2008/0242 [817], andXSH/TC2-2008/0243 [943] are applied.
return to top of page