QUESTION
Do a name and its metadata returned by readdir form a consistent point-in-time snapshot?
getdents64 fills a buffer with multiple linux_dirent64 records starting at the directory file position. glibc readdir presents those entries to userspace one at a time. Each call advances the filesystem directory iterator, but does not lock out creation, deletion, or rename by another process.
d_type is convenience information and may be DT_UNKNOWN. Code that requires security or accuracy should use a directory fd with fstatat/openat rather than reassembling an absolute path from the name string.
STRUCTURE
Structure diagram
Follow each record's d_reclen to find the next entry. Adding only the d_name length fails to skip alignment padding.
CALL PATH
Call path
A directory stream is not an immutable snapshot of names. At the point each entry is processed, resolve the required object again with a dirfd-relative syscall.
This diagram is not for memorizing function names. Follow which return value, file descriptor, memory mapping, or wait queue is passed to the next stage.
SOURCE COORDINATES
Linux 6.18.37 LTS source locations
Go beyond the glibc function to the files where the syscall implementation meets kernel objects. Each link points to the original file at the same tag.
| File | Function / structure | What to inspect |
|---|---|---|
| fs/readdir.c | iterate_dir(), getdents64(), filldir64() | Directory callback and userspace-record construction |
| fs/namei.c | vfs_statx(), filename_lookup() | Revalidate an entry name against the actual path and metadata |
| include/linux/dirent.h | linux_dirent64 | record length, type, offset ABI |
COMPLETE PROGRAM
Complete runnable example
The code below is not pseudocode with explanatory lines omitted. It is a minimal example that can be built and run as a file.
cc -std=c17 -Wall -Wextra -O2 list_dir.c -o list_dir01#define _DEFAULT_SOURCE
02#include <dirent.h>
03#include <errno.h>
04#include <fcntl.h>
05#include <stdio.h>
06#include <sys/stat.h>
07
08int main(int argc, char **argv)
09{
10 const char *path = argc > 1 ? argv[1] : ".";
11 DIR *dir = opendir(path);
12 if (dir == NULL)
13 return 1;
14 int dfd = dirfd(dir);
15
16 errno = 0;
17 struct dirent *entry;
18 while ((entry = readdir(dir)) != NULL) {
19 struct stat st;
20 if (fstatat(dfd, entry->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
21 if (errno == ENOENT)
22 continue;
23 perror("fstatat");
24 break;
25 }
26 printf("%-24s inode=%llu mode=%o\n", entry->d_name,
27 (unsigned long long)st.st_ino, st.st_mode & 07777);
28 }
29 if (entry == NULL && errno != 0)
30 perror("readdir");
31 return closedir(dir) != 0;
32}
RUN RESULT
Run results
The example was run on x86_64 Linux.
Execution environment
Built and run on 2026-11-04 on x86_64 Debian (Linux 6.12.94, gcc 14.2.0, glibc 2.41, -std=c17). This differs from the article baseline (ARM64, Linux 6.18.37 LTS), so PIDs, inodes, and addresses differ from run to run.
Before the fix, the code failed to compile because AT_SYMLINK_NOFOLLOW was undeclared. The code above adds #include <fcntl.h>; the fixed program lists entries in the order returned by getdents64 (excerpt).
$ cc -std=c17 -Wall -Wextra -O2 list_dir.c -o list_dir # before the fix
list_dir.c:19:46: error: ‘AT_SYMLINK_NOFOLLOW’ undeclared (first use in this function)
$ ./list_dir . # after adding #include <fcntl.h>
run.log inode=538698 mode=644
.. inode=430959 mode=755
list_dir.c inode=538399 mode=644
. inode=538398 mode=755

ARM64 execution result
The example was also run in an ARM64 emulator (QEMU, Cortex-A53).

Output as text
This image displays the saved execution log.
. inode=560 mode=755
.. inode=559 mode=755
example-link inode=562 mode=777
example.txt inode=561 mode=644
Verification harness exit status: 0Execution environment
The same C example was cross-compiled for ARM64 and executed on 2026-11-04 in QEMU virt with an emulated Cortex-A53 (TCG, 2 vCPUs, 512 MiB). The guest ran Linux 6.18.58-0-virt, not the article baseline 6.18.37. GCC 15.2.0 and glibc 2.43 were used with static linking; the guest shell and utilities came from Alpine 3.23.7.
The guest ran as root, used loopback only, and had no host disk mounts. This checks the example's observed behavior, not physical hardware timing or every kernel-internal path.
The source above is unchanged. Cross-compiled on the x86_64 host and executed inside the ARM64 guest; static linking was added for the isolated guest. UAPI build headers were 7.0.0, which does not change the running kernel version.
aarch64-linux-gnu-gcc-15 -static -std=c17 -Wall -Wextra -O2 list_dir.c -o list_dir
mkdir entries
printf 'sample\n' > entries/example.txt
chmod 644 entries/example.txt
ln -s example.txt entries/example-link
/examples/list_dir entries
Commands and captured output · Environment and hashes · Full guest boot and run log
CODE NOTES
Code notes
DIR *dir = opendirA DIR is a libc object that owns not only an fd but also a getdents buffer and current position. Avoid traversing the same stream concurrently from multiple threads.
int dfd = dirfdCalls fstatat relative to the same directory object without joining pathnames. The base object remains valid even if the directory is renamed.
errno = 0A NULL from readdir can mean either EOF or error, so set errno to 0 before the loop and distinguish the cases after it ends.
AT_SYMLINK_NOFOLLOWWhen an entry is a symlink, reads metadata for the symlink inode rather than its target. Do not trust d_type alone.
errno == ENOENTAllows the normal race in which another process deletes an entry between readdir and fstatat, then proceeds to the next item.
DETAILS
Detailed behavior
Record lengths are variable
Follow linux_dirent64.d_reclen to find the next record. A raw parser that advances by sizeof(struct dirent) is wrong because names and alignment change the length.
Using glibc readdir avoids direct ABI parsing, but its returned pointer may be overwritten by the next readdir call.
Results can be duplicated or omitted while a directory changes
A filesystem uses iterator cookies and hash/tree positions. A rename or insertion during traversal may make an old entry appear again or a new one be missed; there is no portable snapshot guarantee.
An exact inventory requires one of a higher-level protocol that prevents changes, a filesystem snapshot, or repeated validation.
A recursive walk must manage fd count and symlink policy
Open each child directory with openat and put it on a stack/queue to traverse without changing cwd. Keeping too many directory fds open at once can hit RLIMIT_NOFILE, so define a depth-first close policy.
Make mount-crossing, symlink-following, and bind-mount-cycle policies explicit using device/inode pairs and openat2 resolve flags.
OBJECTS
Objects and lifetimes
| Object | Creation and release | Values to inspect |
|---|---|---|
DIR stream | Created by opendir; its internal fd and buffer are released by closedir | fd, buffer, position |
dirent record | May be valid only from a readdir return until the next operation on the stream | d_name, d_ino, d_type |
directory fd | A number borrowed from dirfd and owned by closedir | Do not close separately; decide whether dup is required |
FAILURE PATH
Failure conditions and common misconceptions
| Observed symptom | Likely causes | How to verify |
|---|---|---|
| Entries occasionally disappear | Concurrent rename/unlink during traversal | Check the source of changes and snapshot requirements |
| File type is UNKNOWN | The filesystem does not provide d_type | Confirm with fstatat |
| A readdir error is treated as EOF | errno was not distinguished | Check for the errno=0 pattern before the loop |
LAB
Verify it yourself
- While traversing a large directory, have another process create and rename files and record the possibility of duplicates and omissions.
- Use strace to confirm that one getdents64 call is decomposed into several readdir results.
- Write a recursive walker using only openat/fstatat and expose symlink and mount-crossing policies as separate options.
./list_dir .strace -e trace=openat,getdents64,newfstatat,close ./list_dir .PRIMARY REFERENCES