OPEN(2)
β¨ OPEN(2) β¨ β the System Calls Manual girlies' edition π
okay so bestie, we're doing open(2) today, from the System Calls Manual, and honestly? this is THE foundational baddie of the whole Unix friend group. every file you've ever touched got opened first. no cap.
πΈ NAME πΈ
open, openat β open or create a file for reading, writing or executing
like... that's the whole job. open the file. or make the file. or both. iconic behaviour tbh.
π LIBRARY π
Standard C Library (libc, -lc)
yeah she lives in libc, as she should π
π¦ SYNOPSIS π¦
#include <fcntl.h>
int
open(const char *path, int flags, ...);
int
openat(int fd, const char *path, int flags, ...);
look at her. two little functions. one giant ... that you only feed when you're being β¨extraβ¨ (aka creating a file). we'll get there.
π DESCRIPTION π
okay so here's the tea. the file name you pass in path gets opened for either execution or reading and/or writing, and which one you get is decided by the flags argument. then a file descriptor gets handed back to the calling process. that fd is your lil ticket to ride ποΈ
and flags can also say "bestie if this file doesn't exist, just make it" β that's the O_CREAT flag doing its thing. but heads up: when you use O_CREAT, open() and openat() need one more argument, a mode_t mode, and the file gets created with that mode, exactly as described in chmod(2), and then modified by your process' umask (peep umask(2) for that whole situation).
β¨ openat() β the plot twist β¨
openat() is literally the same function as open() EXCEPT when path is a relative path. in that case, the file gets resolved relative to the directory associated with the file descriptor fd, not relative to the current working directory. so you're like "open this, but from over there, not from here."
the flags parameter and the optional fourth parameter match open()'s parameters exactly. no notes, they're identical.
and if you pass the special value AT_FDCWD as fd? then the current working directory gets used and the behaviour is identical to a plain call to open(). cute.
π¨ capsicum(4) capability mode π¨
okay this is the serious one, listen up:
- in
capsicum(4)capability mode,open()is not permitted. full stop. - the path argument to
openat()must be strictly relative to a file descriptorfd, as defined insys/kern/vfs_lookup.c. - path must not be an absolute path and must not contain
".."components. - also, no symbolic link in path may contain
".."components either. - and
fdmust not beAT_FDCWD.
this is the "no sneaking out of the sandbox" rule. respect it or the kernel will respectfully decline you π
β¨ OPTIONS β¨
the flags are formed by or'ing these values together. mix and match like a build-your-own-bowl situation π₯£
O_RDONLYβ open for reading onlyO_WRONLYβ open for writing onlyO_RDWRβ open for reading and writingO_EXECβ open for execute onlyO_SEARCHβ open for search only, an alias forO_EXECO_NONBLOCKβ do not block on openO_APPENDβ append on each writeO_CREATβ create file if it does not existO_TRUNCβ truncate size to 0O_EXCLβ error if create and file existsO_SHLOCKβ atomically obtain a shared lockO_EXLOCKβ atomically obtain an exclusive lockO_DIRECTβ eliminate or reduce cache effectsO_FSYNCβ synchronous writesO_SYNCβ synchronous writesO_NOFOLLOWβ do not follow symlinksO_NOCTTYβ ignoredO_TTY_INITβ ignoredO_DIRECTORYβ error if file is not a directoryO_CLOEXECβ setFD_CLOEXECupon openO_VERIFYβ verify the contents of the file
the lore behind each flag π§
okay now let's actually talk about them one by one because the one-liners are NOT the whole story.
O_APPEND β opening a file with O_APPEND set makes every single write on that file get appended to the end. it's giving "no matter where the cursor wanders, you end up at the back of the line."
O_TRUNC β if O_TRUNC is specified and the file exists, the file is truncated to zero length. boom. gone. empty. hope that's what you wanted.
O_EXCL + O_CREAT β if O_EXCL is set together with O_CREAT and the file already exists, open() returns an error. and this is actually useful! it can be used to implement a simple exclusive access locking mechanism. love a two-for-one.
also: if O_EXCL is set and the last component of the pathname is a symbolic link, open() will fail β even if that symbolic link points to a non-existent name. yeah. even then. no exceptions.
O_NONBLOCK β if the O_NONBLOCK flag is specified and the open() system call would otherwise leave the process blocked for some reason (the example given is waiting for carrier on a dialup line, which is a vibe), open() returns immediately. and the descriptor stays in non-blocking mode for subsequent operations. it doesn't just apply to the open, it commits.
O_FSYNC β if O_FSYNC is used in the mask, all writes will immediately and synchronously be written to disk. no buffering games. straight to disk. your data is SAFE but your speed said bye π
O_SYNC β O_SYNC is a synonym for O_FSYNC, required by POSIX. same girl, different name tag.
O_NOFOLLOW β if O_NOFOLLOW is used in the mask and the target file you passed to open() is a symbolic link, then the open() will fail. we do not follow. we do not chase. we stand on business π
O_SHLOCK / O_EXLOCK β when opening a file, you can grab a lock with flock(2) semantics by setting O_SHLOCK for a shared lock, or O_EXLOCK for an exclusive lock. and if you're creating a file with O_CREAT, the request for the lock will never fail β provided that the underlying file system supports locking. (that proviso is doing a LOT of heavy lifting there, bestie. read it twice.)
O_DIRECT β O_DIRECT can be used to minimize or eliminate the cache effects of reading and writing. the system will try to avoid caching the data you read or write. if it can't avoid caching it, it will at least minimize the impact that data has on the cache. use of this flag can drastically reduce performance if not used with care. i'm serious. careful. don't just slap it on everything.
O_NOCTTY β O_NOCTTY can be used to make sure the OS does not assign this file as the controlling terminal when it opens a tty device. this is the default on FreeBSD, but it's present for POSIX compatibility. the open() system call will not assign controlling terminals on FreeBSD. so like... she's here for the plot, not because she's needed.
O_TTY_INIT β O_TTY_INIT can be used to make sure the OS restores the terminal attributes when initially opening a TTY. this is also the default on FreeBSD, but present for POSIX compatibility. the initial call to open() on a TTY will always restore default terminal attributes on FreeBSD. again: present, polite, not required.
O_DIRECTORY β O_DIRECTORY can be used to ensure the resulting file descriptor refers to a directory. and here's why it matters: this flag can be used to prevent applications with elevated privileges from opening files which are even unsafe to open with O_RDONLY, such as device nodes. yes. even O_RDONLY can be dangerous. this is the seatbelt flag. π
O_CLOEXEC β O_CLOEXEC can be used to set the FD_CLOEXEC flag for the newly returned file descriptor. tidy. no leaks across exec.
O_VERIFY β O_VERIFY can be used to indicate to the kernel that the contents of the file should be verified before allowing the open to proceed. the details of what "verified" means is implementation specific β so it's giving mystery, it's giving β¨unspecifiedβ¨. the run-time linker (rtld) uses this flag to ensure shared objects have been verified before operating on them.
π O_SEARCH and the fd rules π
when fd is opened with O_SEARCH, execute permissions are checked at open time. that fd may not be used for any read operations like getdirentries(2). the primary use for this descriptor will be as the lookup descriptor for the *at() family of functions. she's a pointer, not a reader. know the difference.
β what you get back β
if successful, open() returns a non-negative integer, termed a file descriptor. it returns -1 on failure. and the file pointer used to mark the current position within the file is set to the beginning of the file. every time. fresh start energy π
π signal interruption tea π
if a sleeping open of a device node from devfs(5) is interrupted by a signal, the call always fails with EINTR β even if the SA_RESTART flag is set for the signal. no restarts. no do-overs. nope.
but a sleeping open of a fifo (see mkfifo(2)) is restarted as normal. so fifos get grace, device nodes don't. that's just how it is. π
ownership & fd lifecycle π«Ά
when a new file is created, it is given the group of the directory which contains it. not your group. the directory's group. the directory is the parent here, literally.
and unless the O_CLOEXEC flag was specified, the new descriptor is set to remain open across execve(2) system calls β see close(2), fcntl(2) and the O_CLOEXEC description. so if you didn't say cloexec, that fd is coming with you into the next program. uninvited. π
the limit π
the system imposes a limit on the number of file descriptors open simultaneously by one process. the getdtablesize(2) system call returns the current system limit. so if you're getting weird failures after opening a zillion files... that's why. it's not you, it's the limit.
π₯ RETURN VALUES π₯
if successful, open() and openat() return a non-negative integer, termed a file descriptor. they return -1 on failure, and set errno to indicate the error.
that's it. that's the contract. -1 means check errno, always, every time, no cap. π
The named file is opened unlessβ¦ okay bestie, buckle up, this is the part where the kernel says "no π
" and hands you an errno. Every single one of these is a whole mood:
[ENOTDIR]β a component of the path prefix is not a directory. Rude. π[ENAMETOOLONG]β a component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters. Your filename is doing too much, fr fr.[ENOENT]βO_CREATis not set and the named file does not exist. It's giving "ghosted by the filesystem".[ENOENT]β a component of the path name that must exist does not exist.[EACCES]β search permission is denied for a component of the path prefix.[EACCES]β the required permissions (for reading and/or writing) are denied for the given flags.[EACCES]βO_TRUNCis specified and write permission is denied.[EACCES]βO_CREATis specified, the file does not exist, and the directory in which it is to be created does not permit writing.[EPERM]βO_CREATis specified, the file does not exist, and the directory in which it is to be created has its immutable flag set, see thechflags(2)manual page for more information.[EPERM]β the named file has its immutable flag set and the file is to be modified. Locked, sealed, immovable, iconic π[EPERM]β the named file has its append-only flag set, the file is to be modified, andO_TRUNCis specified orO_APPENDis not specified.[ELOOP]β too many symbolic links were encountered in translating the pathname.[EISDIR]β the named file is a directory, and the arguments specify it is to be modified.[EISDIR]β the named file is a directory, and the flags specifiedO_CREATwithoutO_DIRECTORY.[EROFS]β the named file resides on a read-only file system, and the file is to be modified.[EROFS]βO_CREATis specified and the named file would reside on a read-only file system.[EMFILE]β the process has already reached its limit for open file descriptors. You've hit your ceiling, queen, no more.[ENFILE]β the system file table is full.[EMLINK]βO_NOFOLLOWwas specified and the target is a symbolic link.[ENXIO]β the named file is a character special or block special file, and the device associated with this special file does not exist.[ENXIO]βO_NONBLOCKis set, the named file is a fifo,O_WRONLYis set, and no process has the file open for reading.[EINTR]β theopen()operation was interrupted by a signal. Rude interruption, honestly.[EOPNOTSUPP]βO_SHLOCKorO_EXLOCKis specified but the underlying file system does not support locking.[EOPNOTSUPP]β the named file is a special file mounted through a file system that does not support access to it (e.g. NFS).[EWOULDBLOCK]βO_NONBLOCKand one ofO_SHLOCKorO_EXLOCKis specified and the file is locked.[ENOSPC]βO_CREATis specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because there is no space left on the file system containing the directory.[ENOSPC]βO_CREATis specified, the file does not exist, and there are no free inodes on the file system on which the file is being created.[EDQUOT]βO_CREATis specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because the user's quota of disk blocks on the file system containing the directory has been exhausted.[EDQUOT]βO_CREATis specified, the file does not exist, and the user's quota of inodes on the file system on which the file is being created has been exhausted.[EIO]β an I/O error occurred while making the directory entry or allocating the inode forO_CREAT.[EINTEGRITY]β corrupted data was detected while reading from the file system.[ETXTBSY]β the file is a pure procedure (shared text) file that is being executed and theopen()system call requests write access.[EFAULT]β the path argument points outside the process's allocated address space.[EEXIST]βO_CREATandO_EXCLwere specified and the file exists.[EOPNOTSUPP]β an attempt was made to open a socket (not currently implemented).[EINVAL]β an attempt was made to open a descriptor with an illegal combination ofO_RDONLY,O_WRONLY, orO_RDWR, andO_EXECorO_SEARCH.[EBADF]β the path argument does not specify an absolute path and the fd argument is neitherAT_FDCWDnor a valid file descriptor open for searching.[ENOTDIR]β the path argument is not an absolute path and fd is neitherAT_FDCWDnor a file descriptor associated with a directory.[ENOTDIR]βO_DIRECTORYis specified and the file is not a directory.[ECAPMODE]βAT_FDCWDis specified and the process is in capability mode.[ECAPMODE]βopen()was called and the process is in capability mode.[ENOTCAPABLE]β path is an absolute path or contained a".."component leading to a directory outside of the directory hierarchy specified by fd.
π SEE ALSO π
Squad goals, the whole friend group π«Ά
chmod(2), close(2), dup(2), fexecve(2), fhopen(2), getdtablesize(2), getfh(2), lgetfh(2), lseek(2), read(2), umask(2), write(2), fopen(3), capsicum(4)
π STANDARDS π
These functions are specified by IEEE Std 1003.1-2008 ("POSIX.1").
And here's the tea: FreeBSD sets errno to EMLINK instead of ELOOP as specified by POSIX when O_NOFOLLOW is set in flags and the final component of pathname is a symbolic link, so it can tell that apart from the case of too many symbolic link traversals in one of its non-final components. Different error, same chaos π
π¦ HISTORY π¦
The open() function appeared in Version 1 AT&T UNIX. Yes, it's that old β vintage, antique, still serving looks. The openat() function was introduced in FreeBSD 8.0. β¨
π BUGS π
The Open Group Extended API Set 2 specification requires that the test for whether fd is searchable is based on whether fd is open for searching, not whether the underlying directory currently permits searches. The present implementation of the openat checks the current permissions of directory instead. So yeah, that's a known little discrepancy, no cap π«
and that's the whole page, bestie!! go forth and open files responsibly π
This is the Debian edition, dated March 30, 2020, and it's the OPEN(2) page. Love that for us. π
π¦ where this page comes from
- debian bookworm: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- debian trixie: freebsd-manpages 12.2-2 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu jammy: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu noble: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu questing: freebsd-manpages 12.2-2
- ubuntu resolute: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu stonking: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- Copyright (c) 1980, 1991, 1993 The Regents of the University of California. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms