File & I/O · Section 2
openat(2)
Open a file relative to a directory file descriptor — the modern replacement for open().
Signature
#include <fcntl.h>
int openat(int dirfd, const char * pathname, int flags, mode_t mode);- dirfd
- Directory descriptor that anchors pathname when pathname is relative. AT_FDCWD means "use the process's current working directory". With an absolute pathname dirfd is ignored, even if it is not a valid descriptor.
- pathname
- Path of the file to open. If absolute, dirfd is ignored. If relative, dirfd anchors it.
- flags
- Same as open(): access mode ORed with creation/status flags (O_CREAT, O_CLOEXEC, etc.).
- mode
- File-permission bits applied only with O_CREAT or O_TMPFILE.
Description
openat() opens the file at pathname, but interprets pathname relative to the directory referred to by dirfd instead of the calling process's current working directory. With dirfd == AT_FDCWD, openat() behaves exactly like open(). The other arguments — flags, mode — are identical to open(). Modern glibc implements open() via openat() with AT_FDCWD; on aarch64 the legacy open() syscall doesn't exist at all, only openat() and openat2(). Beyond convenience, openat() is the building block of race-free filesystem operations: holding dirfd over an O_DIRECTORY open lets you traverse a tree without recomposing absolute paths between hops, immune to symlink swaps and rename races at higher directory levels.
What AT_FDCWD means
AT_FDCWD is a sentinel you pass as dirfd to say "resolve a relative pathname against the current working directory", exactly as open() does. It is defined in <fcntl.h> as -100, a value that can never be a real file descriptor. The full resolution rule for openat() is:
| pathname | dirfd | Resolved relative to |
|---|---|---|
Absolute (/etc/passwd) | anything | / (dirfd is ignored) |
Relative (config.toml) | AT_FDCWD | The process's current working directory |
| Relative | A directory fd | That directory, wherever it now lives |
| Relative | Not a valid fd | Fails with EBADF |
| Relative | An fd that is not a directory | Fails with ENOTDIR |
That is why almost every line of strace output for file access starts with openat(AT_FDCWD, ...: glibc implements open() as openat(AT_FDCWD, ...), and on aarch64 and other newer architectures there is no open syscall at all. Add -y and strace prints the directory AT_FDCWD stands for:
$ strace -y -e trace=openat ./demo d report.txt
openat(AT_FDCWD</home/me/project>, "d", O_RDONLY|O_CLOEXEC|O_PATH|O_DIRECTORY) = 3</home/me/project/d>
openat(3</home/me/project/d>, "report.txt", O_RDONLY|O_NOFOLLOW|O_CLOEXEC) = 4</home/me/project/d/report.txt>The same AT_FDCWD sentinel is accepted by every *at() call: fstatat/newfstatat, statx, unlinkat, mkdirat, renameat2, linkat, readlinkat, faccessat, execveat and more.
openat flags that matter
flags is one access mode (O_RDONLY, O_WRONLY or O_RDWR) ORed with creation and status flags. These are the ones that change behavior in ways people search for:
| Flag | Since | What it does |
|---|---|---|
O_CLOEXEC | 2.6.23 | Sets close-on-exec atomically. Use it on every open in multithreaded code: a separate fcntl(F_SETFD) leaves a window where a concurrent fork() + execve() leaks the fd to the child. |
O_DIRECTORY | 2.1.126 | Fails with ENOTDIR unless the path is a directory. Use it when opening a dirfd. |
O_NOFOLLOW | 2.1.126 | Fails with ELOOP if the last component is a symlink. Symlinks earlier in the path are still followed. |
O_PATH | 2.6.39 | Returns a descriptor that names a location without opening the file: no read permission needed on the object itself, but read()/write() fail with EBADF. Ideal as a dirfd. Only O_CLOEXEC, O_DIRECTORY and O_NOFOLLOW are honored alongside it. |
O_TMPFILE | 3.11 | pathname names a directory; creates an unnamed regular file in it, lost on close unless you give it a name with linkat(). Must be combined with O_RDWR or O_WRONLY. Needs filesystem support (ext4, XFS, Btrfs, tmpfs and others). |
O_CREAT / O_EXCL | Create the file; with O_EXCL, fail with EEXIST if it already exists. The only race-free "create if absent". | |
O_NONBLOCK | Do not block on FIFOs and character devices. No effect on regular files and block devices. |
openat() silently ignores unknown bits in flags. openat2() rejects them with EINVAL, which is one of the reasons it exists.
Race-free file access with a directory fd
Paths are re-resolved on every call. If your program checks /srv/uploads/user/report.txt and then opens it, any component of that path (including uploads and user) can be swapped for a symlink in between. Holding a descriptor to the directory pins it: the fd keeps referring to the same directory even if it is renamed, and relative opens through it never walk the upper components again.
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/openat2.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
const char *root = argc > 1 ? argv[1] : "/srv/uploads";
const char *name = argc > 2 ? argv[2] : "report.txt";
/* 1. Pin the directory once. O_PATH: no read permission needed on it. */
int dirfd = open(root, O_PATH | O_DIRECTORY | O_CLOEXEC);
if (dirfd == -1) { perror(root); return 1; }
/* 2. openat(): relative to dirfd, refuse a symlink in the last component. */
int fd = openat(dirfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
if (fd == -1) perror("openat");
else close(fd);
/* 3. openat2(): refuse to leave dirfd at all ("../", absolute symlinks). */
struct open_how how = {
.flags = O_RDONLY | O_CLOEXEC,
.resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS,
};
fd = syscall(SYS_openat2, dirfd, name, &how, sizeof how);
if (fd == -1) perror("openat2");
else close(fd);
close(dirfd);
return 0;
}O_NOFOLLOW alone is not a sandbox. Run the program above against a directory d that contains a regular file, a symlink to /etc/passwd, and with a ../ name:
openat(3, "report.txt", O_RDONLY|O_NOFOLLOW|O_CLOEXEC) = 4
openat2(3, "report.txt", {flags=O_RDONLY|O_CLOEXEC, resolve=RESOLVE_NO_MAGICLINKS|RESOLVE_BENEATH}, 24) = 4
openat(3, "link", O_RDONLY|O_NOFOLLOW|O_CLOEXEC) = -1 ELOOP (Too many levels of symbolic links)
openat2(3, "link", {flags=O_RDONLY|O_CLOEXEC, resolve=RESOLVE_NO_MAGICLINKS|RESOLVE_BENEATH}, 24) = -1 EXDEV (Invalid cross-device link)
openat(3, "../openat_demo.c", O_RDONLY|O_NOFOLLOW|O_CLOEXEC) = 4
openat2(3, "../openat_demo.c", {flags=O_RDONLY|O_CLOEXEC, resolve=RESOLVE_NO_MAGICLINKS|RESOLVE_BENEATH}, 24) = -1 EXDEV (Invalid cross-device link)openat() happily escapes with ../. Only openat2() with RESOLVE_BENEATH keeps every step of the resolution under dirfd, and it reports an escape attempt as EXDEV.
open vs openat vs openat2
open() | openat() | openat2() | |
|---|---|---|---|
| Since | Original Unix call | 2.6.16 | 5.6 |
| Relative paths resolved against | Current directory | dirfd (or cwd with AT_FDCWD) | dirfd (or cwd with AT_FDCWD) |
| Arguments | pathname, flags, mode | dirfd, pathname, flags, mode | dirfd, pathname, struct open_how *, size |
| Unknown flags | Ignored | Ignored | EINVAL |
| Path resolution control | None | O_NOFOLLOW (last component only) | RESOLVE_* flags for every component |
| glibc wrapper | Yes (calls openat) | Yes | No, use syscall(SYS_openat2, ...) |
| Syscall exists on aarch64 | No | Yes | Yes |
The resolve field of struct open_how takes these flags (see openat2):
| RESOLVE_ flag | Rejects |
|---|---|
RESOLVE_BENEATH | Any resolution step outside dirfd: .. above it, absolute paths, absolute symlinks (EXDEV) |
RESOLVE_IN_ROOT | Escapes are clamped rather than rejected: dirfd acts as / for this lookup (.. and absolute symlinks stay inside), like a per-call chroot() |
RESOLVE_NO_SYMLINKS | Any symlink in any component (ELOOP), unlike O_NOFOLLOW which only checks the last one |
RESOLVE_NO_MAGICLINKS | /proc/PID/fd/*, /proc/PID/exe and similar magic links (ELOOP), a known container-escape path |
RESOLVE_NO_XDEV | Crossing a mount point, bind mounts included (EXDEV) |
RESOLVE_CACHED (5.12) | Any lookup that needs revalidation or I/O (EAGAIN): a fast-path open that never blocks, retried without the flag on failure |
Use openat() for ordinary code and as the portable building block. Reach for openat2() when you open untrusted relative paths under a fixed directory: file servers, archive extractors, container runtimes resolving paths inside a rootfs.
Tracing openat
- Which files does a program open, and which are missing?
strace -f -e trace=openat,open,openat2 -Z ./appprints only the failed ones (-Zis--failed-only). - Every file-related call, not just opens:
strace -e trace=%file ./appalso catchesstatx,newfstatat,access,readlink. - System-wide, without ptrace overhead:
bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args.filename)); }'.
See the strace cheat sheet for reading the output.
Architecture mapping
| Architecture | Number | ABI | Entry point |
|---|---|---|---|
| x86 (i386) | 295 | i386 | sys_openat |
| x64 (x86_64) | 257 | common | sys_openat |
| ARM64 (aarch64) | 56 | — | sys_openat |
Kernel history
Introduced in Linux 2.6.16.
2.6.16
openat() was added in 2.6.16 alongside the broader *at family (fstatat, fchmodat, unlinkat, etc.) to enable race-free traversals and per-thread working directories independent of chdir().
5.6
openat2() (Linux 5.6) extends openat() with an open_how struct carrying resolve flags such as RESOLVE_NO_SYMLINKS, RESOLVE_NO_MAGICLINKS, RESOLVE_BENEATH, and RESOLVE_IN_ROOT — letting servers safely open paths under a fixed directory without chroot.
seccomp & containers
Docker default profile
Allowed
Podman default profile
Allowed
openat() is on every default profile. Blocking it kills the process — modern libc cannot open any file without it. Argument filtering on dirfd is awkward because file descriptors are dynamic; the practical lever is filtering openat2() resolve flags or pairing openat() restrictions with Landlock for path-level confinement.
libseccomp
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat), 0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat2), 0);strace example
$ strace -e openat ls /etc
openat(AT_FDCWD, "/etc", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 3
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3Most code paths reach openat() rather than open() because glibc rewrites the call. strace prints the dirfd as AT_FDCWD when applicable, and pretty-prints flags. -y resolves dirfd to its directory path; -e trace=openat,open,openat2 filters the family together.
Security & observability
openat() is the modern observation point for every file open on Linux. eBPF tracepoint sys_enter_openat (and the LSM hook file_open) captures the dirfd, full pathname, and flags. Rootkits commonly hook openat() to hide files matching their patterns from ls / find — the kernel-level audit trail diverges from the userspace view, which is the canonical detection. The *at family also enables tighter sandboxing: a process can pre-open a directory descriptor, drop other privileges, and continue to access only paths under that directory via openat() — a poor-man's chroot.
Errors
- EACCES
- Search permission denied on a component, or the file is not readable/writable as requested.
- EBADF
- dirfd is neither AT_FDCWD nor a valid descriptor.
- EEXIST
- —
- ENOENT
- A component of pathname does not exist, or O_CREAT was not set and the file is missing.
- ENOTDIR
- pathname is relative and dirfd refers to a non-directory.
- EISDIR
- —
- ELOOP
- —
- ENAMETOOLONG
- —
- EMFILE
- —
- ENFILE
- —
Flags
- AT_FDCWD
- -100
- Sentinel value for dirfd meaning "current working directory". Defined as -100 in <fcntl.h>.
- AT_EMPTY_PATH
- 0x1000
- When set (Linux 2.6.39+), an empty pathname operates on dirfd itself — useful with O_PATH descriptors for fstatat/linkat. Requires CAP_DAC_READ_SEARCH outside the process.
- AT_SYMLINK_NOFOLLOW
- 0x100
- Don't dereference the final component if it is a symlink.