| Skip Navigation Links | |
| Exit Print View | |
![]() | man pages section 2: System Calls Oracle Solaris 11 Information Library |
- open a file
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>intopen(const char *path,intoflag,/* mode_tmode */);
intopenat(intfildes,const char *path,intoflag,/* mode_tmode */);
Theopen() function establishes the connection between a file and a filedescriptor. It creates an open file description that refers to a fileand a file descriptor that refers to that open file description. Thefile descriptor is used by other I/O functions to refer to that file.Thepath argument points to a pathname naming the file.
Theopenat() function is identical to theopen() function except that thepath argument is interpreted relative to the starting point implied by thefildes argument. If thefildes argument has the special valueAT_FDCWD, a relativepath argument will be resolved relative to the current working directory. Ifthepath argument is absolute, thefildes argument is ignored.
Theopen() function returns a file descriptor for the named file thatis the lowest file descriptor not currently open for that process. Theopen file description is new, and therefore the file descriptor does notshare it with any other process in the system. TheFD_CLOEXEC filedescriptor flag associated with the new file descriptor is cleared.
The file offset used to mark the current position within the fileis set to the beginning of the file.
The file status flags and file access modes of the open filedescription are set according to the value ofoflag. Themode argumentis used only whenO_CREAT is specified (see below.)
Values foroflag are constructed by a bitwise-inclusive-OR of flags from thefollowing list, defined in <fcntl.h>. Applications must specify exactly one of thefirst five values (file access modes) below in the value ofoflag:
Open for reading only.
Open for writing only.
Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
Open ordinary file for execute only.
Open directory for search only.
Any combination of the following may be used:
If set, the file offset is set to the end of the file prior to each write.
If set, theFD_CLOEXEC flag is set for the new file descriptor.
Create the file if it does not exist. This flag requires that themode argument be specified.
If the file exists, this flag has no effect except as noted underO_EXCL below. Otherwise, the file is created with the user ID of the file set to the effective user ID of the process. The group ID of the file is set to the effective group IDs of the process, or if theS_ISGID bit is set in the directory in which the file is being created, the file's group ID is set to the group ID of its parent directory. If the group ID of the new file does not match the effective group ID or one of the supplementary groups IDs, theS_ISGID bit is cleared. The access permission bits (see<sys/stat.h>) of the file mode are set to the value ofmode, modified as follows (seecreat(2)): a bitwise-AND is performed on the file-mode bits and the corresponding bits in the complement of the process's file mode creation mask. Thus, all bits set in the process's file mode creation mask (seeumask(2)) are correspondingly cleared in the file's permission mask. The “save text image after execution bit” of the mode is cleared (seechmod(2)).O_SYNC Write I/O operations on the file descriptor complete as defined by synchronized I/O file integrity completion (seefcntl.h(3HEAD) definition ofO_SYNC.) When bits other than the file permission bits are set, the effect is unspecified. Themode argument does not affect whether the file is open for reading, writing or for both.
Ifpath does not specify a directory, fail and seterrno toENOTDIR.
Write I/O operations on the file descriptor complete as defined by synchronized I/O data integrity completion.
IfO_CREAT andO_EXCL are set,open() fails if the file exists. The check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other threads executingopen() naming the same filename in the same directory withO_EXCL andO_CREAT set. IfO_EXCL andO_CREAT are set, and path names a symbolic link,open() fails and setserrno toEEXIST, regardless of the contents of the symbolic link. IfO_EXCL is set andO_CREAT is not set, the result is undefined.
If set, the offset maximum in the open file description is the largest value that can be represented correctly in an object of typeoff64_t.
If set andpath identifies a terminal device,open() does not cause the terminal device to become the controlling terminal for the process.
If the path names a symbolic link,open() fails and setserrno toELOOP.
If the link count of the named file is greater than 1,open() fails and setserrno toEMLINK.
These flags can affect subsequent reads and writes (seeread(2) andwrite(2)). If bothO_NDELAY andO_NONBLOCK are set,O_NONBLOCK takes precedence.
When opening a FIFO withO_RDONLY orO_WRONLY set:
IfO_NONBLOCK orO_NDELAY is set, anopen() for reading only returns without delay. Anopen() for writing only returns an error if no process currently has the file open for reading.
IfO_NONBLOCK andO_NDELAY are clear, anopen() for reading only blocks until a thread opens the file for writing. Anopen() for writing only blocks the calling thread until a thread opens the file for reading.
After both ends of a FIFO have been opened, there is no guarantee that further calls toopen()O_RDONLY (O_WRONLY) will synchronize with later calls toopen()O_WRONLY (O_RDONLY) until both ends of the FIFO have been closed by all readers and writers. Any data written into a FIFO will be lost if both ends of the FIFO are closed before the data is read.
When opening a block special or character special file that supports non-blocking opens:
IfO_NONBLOCK orO_NDELAY is set, theopen() function returns without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific.
IfO_NONBLOCK andO_NDELAY are clear, theopen() function blocks the calling thread until the device is ready or available before returning.
Otherwise, the behavior ofO_NONBLOCK andO_NDELAY is unspecified.
Read I/O operations on the file descriptor complete at the same level of integrity as specified by theO_DSYNC andO_SYNC flags. If bothO_DSYNC andO_RSYNC are set inoflag, all I/O operations on the file descriptor complete as defined by synchronized I/O data integrity completion. If bothO_SYNC andO_RSYNC are set inoflag, all I/O operations on the file descriptor complete as defined by synchronized I/O file integrity completion.
Write I/O operations on the file descriptor complete as defined by synchronized I/O file integrity completion.
If the file exists and is a regular file, and the file is successfully openedO_RDWR orO_WRONLY, its length is truncated to 0 and the mode and owner are unchanged. It has no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-dependent. The result of usingO_TRUNC withO_RDONLY is undefined.
TheO_TTY_INIT flag is ignored. Terminal devices are always opened in a state providing conforming behavior.
If set inopenat(), a relative path argument is interpreted as a reference to an extended attribute of the file associated with the supplied file descriptor. This flag therefore requires the presence of a legalfildes argument. If set inopen(), the implied file descriptor is that for the current working directory. Extended attributes must be referenced with a relative path; providing an absolute path results in a normal file reference.
IfO_CREAT is set and the file did not previously exist, uponsuccessful completion,open() marks for update thest_atime,st_ctime, andst_mtime fieldsof the file and thest_ctime andst_mtime fields of the parentdirectory.
IfO_TRUNC is set and the file did previously exist, upon successfulcompletion,open() marks for update thest_ctime andst_mtime fields of thefile.
If both theO_SYNC andO_DSYNC flags are set, the effect isas if only theO_SYNC flag was set.
Ifpath refers to a STREAMS file,oflag may be constructed fromO_NONBLOCK orO_NODELAY OR-ed with eitherO_RDONLY,O_WRONLY, orO_RDWR. Other flag valuesare not applicable to STREAMS devices and have no effect on them. The valuesO_NONBLOCK andO_NODELAY affect the operation of STREAMS driversand certain functions (seeread(2),getmsg(2),putmsg(2), andwrite(2)) applied to filedescriptors associated with STREAMS files. For STREAMS drivers, the implementation ofO_NONBLOCKandO_NODELAY is device-specific.
Whenopen() is invoked to open a named stream, and theconnldmodule (seeconnld(7M)) has been pushed on the pipe,open() blocks untilthe server process has issued anI_RECVFDioctl() (seestreamio(7I)) to receivethe file descriptor.
Ifpath names the master side of a pseudo-terminal device, then itis unspecified whetheropen() locks the slave side so that it cannotbe opened. Portable applications must callunlockpt(3C) before opening the slaveside.
If the file is a regular file and the local file systemis mounted with thenbmand mount option, then a mandatory share reservationis automatically obtained on the file. The share reservation is obtained asiffcntl(2) were called withcmdF_SHARE_NBMAND and thefshare_t values setas follows:
Set to the type of read/write access for which the file is opened.
F_NODNY
The file descriptor value returned fromopen().
Ifpath is a symbolic link andO_CREAT andO_EXCL are set,the link is not followed.
Certain flag values can be set followingopen() as described infcntl(2).
The largest value that can be represented correctly in an object oftypeoff_t is established as the offset maximum in the open filedescription.
Upon successful completion, theopen() function opens the file and return anon-negative integer representing the lowest numbered unused file descriptor. Otherwise,-1 isreturned,errno is set to indicate the error, and no files are createdor modified.
Theopen() andopenat() functions will fail if:
Search permission is denied on a component of the path prefix.
The file exists and the permissions specified byoflag are denied.
The file does not exist and write permission is denied for the parent directory of the file to be created.
O_TRUNC is specified and write permission is denied.
The {PRIV_FILE_DAC_SEARCH} privilege allows processes to search directories regardless of permission bits. The {PRIV_FILE_DAC_WRITE} privilege allows processes to open files for writing regardless of permission bits. Seeprivileges(5) for special considerations when opening files owned by UID 0 for writing. The {PRIV_FILE_DAC_READ} privilege allows processes to open files for reading regardless of permission bits.
To open a file for reading or writing, the basic privileges {PRIV_FILE_READ} and {PRIV_FILE_WRITE}, respectively, need to be asserted in the effective set.
A mandatory share reservation could not be obtained because the desired access conflicts with an existingf_deny share reservation.
The file descriptor provided toopenat() is invalid.
The file does not exist,O_CREAT is specified, and either the directory where the new file entry is being placed cannot be extended because the user's quota of disk blocks on that file system has been exhausted, or the user's quota of inodes on the file system where the file is being created has been exhausted.
TheO_CREAT andO_EXCL flags are set and the named file exists.
Thepath argument includes non-UTF8 characters and the file system accepts only file names where all characters are part of the UTF-8 character codeset.
A signal was caught duringopen().
Thepath argument points to an illegal address.
The system does not support synchronized I/O for this file, or theO_XATTR flag was supplied and the underlying file system does not support extended file attributes.
Thepath argument names a STREAMS file and a hangup or error occurred during theopen().
The named file is a directory andoflag includesO_WRONLY orO_RDWR.
Too many symbolic links were encountered in resolvingpath.
A loop exists in symbolic links encountered during resolution of thepath argument.
TheO_NOFOLLOW flag is set and the final component of path is a symbolic link.
There are currently {OPEN_MAX} file descriptors open in the calling process.
TheO_NOLINKS flag is set and the named file has a link count greater than 1.
Components ofpath require hopping to multiple remote machines and the file system does not allow it.
The length of thepath argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
The maximum allowable number of files is currently open in the system.
TheO_CREAT flag is not set and the named file does not exist; or theO_CREAT flag is set and either the path prefix does not exist or thepath argument points to an empty string.
TheO_EXEC access mode was specified and the file to be opened is not an ordinary file.
Thepath argument points to a remote machine, and the link to that machine is no longer active.
Thepath argument names a STREAMS-based file and the system is unable to allocate a STREAM.
The directory or file system that would contain the new file cannot be expanded, the file does not exist, andO_CREAT is specified.
The device specified bypath does not support the open operation.
A component of the path prefix is not a directory, a relative path was supplied toopenat(), theO_XATTR flag was not supplied, and the file descriptor does not refer to a directory, theO_SEARCH access mode was specified and the file to be opened is not a directory, orO_DIRECTORY was specified and thepath argument does not specify a directory.
TheO_NONBLOCK flag is set, the named file is a FIFO, theO_WRONLY flag is set, and no process has the file open for reading; or the named file is a character special or block special file and the device associated with this special file does not exist or has been retired by the fault management framework .
An attempt was made to open a path that corresponds to aAF_UNIX socket.
The named file is a regular file and eitherO_LARGEFILE is not set and the size of the file cannot be represented correctly in an object of typeoff_t orO_LARGEFILE is set and the size of the file cannot be represented correctly in an object of typeoff64_t.
The named file resides on a read-only file system and eitherO_WRONLY,O_RDWR,O_CREAT (if file does not exist), orO_TRUNC is set in theoflag argument.
Theopenat() function will fail if:
The permissions of the directory underlyingfildes do not permit directory searches.
Thepath argument does not specify an absolute path and thefildes argument is neitherAT_FDCWD nor a valid file descriptor open for reading or searching.
Theopen() function may fail if:
Thepath argument names the slave side of a pseudo-terminal device that is locked.
The value of theoflag argument is not valid.
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
Thepath argument names a STREAMS file and the system is unable to allocate resources.
The file is a pure procedure (shared text) file that is being executed andoflag isO_WRONLY orO_RDWR.
Example 1 Open a file for writing by the owner.
The following example opens the file/tmp/file, either by creating it ifit does not already exist, or by truncating its length to 0if it does exist. If the call creates a new file, theaccess permission bits in the file mode of the file are setto permit reading and writing by the owner, and to permit reading onlyby group members and others.
If the call toopen() is successful, the file is opened forwriting.
#include <fcntl.h>...int fd;mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;char *filename = "/tmp/file";...fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, mode);...
Example 2 Open a file using an existence check.
The following example uses theopen() function to try to create theLOCKFILE file and open it for writing. Since theopen() function specifiestheO_EXCL flag, the call fails if the file already exists. Inthat case, the application assumes that someone else is updating the password fileand 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);}...Example 3 Open a file for writing.
The following example opens a file for writing, creating the file ifit does not already exist. If the file does exist, the systemtruncates the file to zero bytes.
#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#define LOCKFILE "/etc/ptmp"...int pfd;char filename[PATH_MAX+1];...if ((pfd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1){ perror("Cannot open output file\n"); exit(1);}...Theopen() function has a transitional interface for 64-bit file offsets. Seelf64(5). Note that usingopen64() is equivalent to usingopen() withO_LARGEFILEset inoflag.
Seeattributes(5) for descriptions of the following attributes:
|
Intro(2),chmod(2),close(2),creat(2),dup(2),exec(2),fcntl(2),getmsg(2),getrlimit(2),lseek(2),putmsg(2),read(2),stat(2),umask(2),write(2),attropen(3C),fcntl.h(3HEAD),stat.h(3HEAD),unlockpt(3C),attributes(5),lf64(5),privileges(5),standards(5),connld(7M),streamio(7I)
Hierarchical Storage Management (HSM) file systems can sometimes cause long delays whenopening a file, since HSM files must be recalled from secondary storage.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.Legal Notices | ![]() ![]() |