Course Onboarding, stat & File Types
Misclassifying sockets as regular files with unmasked st_mode & S_IFREG, chasing symbolic links with stat() into infinite directory loops, or wrapping 32-bit time_t negative in 2038 breaks Linux storage tools. Building on GL-C01, you will decode all seven VFS file types, contrast stat(), fstat(), and lstat(), and query mask-scoped statx().
What you'll learn
- Map the
GL-C01descriptor and ISO C11 baseline intoGL-C02VFS metadata, POSIX signals, processes, and threads. - Decode 16-bit
st_modebitfields viaS_IFMTandS_ISREG..S_ISSOCKmacros across all seven Linux VFS file types. - Compare
stat(),fstat(),lstat(), and mask-scopedstatx()across files, symlinks, and Y2038-safe 64-bit timestamps.
Why Filename Extensions and Naive stat() Calls Fail
Imagine deploying a C telemetry archiver on an embedded Linux gateway that walks /var/run to compress .log files. The engineer tests whether a path is a regular file by checking strstr(name, ".log") and if (st.st_mode & S_IFREG) after calling stat(path, &st). In production, three failures strike within minutes: a UNIX domain socket named audit.log matches st.st_mode & S_IFREG because octal S_IFSOCK (0140000) shares the 0100000 bit with S_IFREG, hanging read() indefinitely; a symbolic link pointing to .. gets dereferenced by stat() as a directory, trapping the scanner in an infinite loop; and on a 32-bit ARMv7 build lacking 64-bit time flags, certificate expiry timestamps past 2038-01-19T03:14:07Z wrap negative.
Naive suffix checks and unmasked bit tests fail because the Linux kernel Virtual Filesystem (VFS) assigns zero semantic meaning to filename extensions and encodes file types as a multi-bit field rather than single-bit flags. This lesson opens Course 2 (GL-C02: Filesystems, Signals, Processes & Threads in C) in the four-course Linux Systems Programming in C track (GL-C01 -> GL-C02 -> GL-C03 -> GL-C04). In GL-C01, you compiled strict ISO C11 code (gcc -std=c11 -Wall -Wextra -Werror) over unbuffered POSIX file descriptors (open, read, write, lseek, close), buffered <stdio.h> streams, and thread-local errno. GL-C02 scales that single-file baseline to whole-system architecture: VFS metadata and directory trees, bounded strings and /proc telemetry, asynchronous POSIX signals, multi-process supervision, and multi-core POSIX threads.
note: Think of a shipping container's stamped steel manifest plate welded onto its frame rather than a paper sticker taped to a warehouse shelf. Even if clerks relabel the shelf slot or hang a directional sign in another aisle, reading the frame plate directly reveals the container's true class, weight, owner, and inspection timestamps.
Where it stops working: Unlike a physical steel plate read by eye, stat(), fstat(), and lstat() copy live VFS struct inode fields from kernel RAM into a caller-supplied struct stat buffer across a privilege-switching system call.
Origin & Formal Definition (inode and stat): Coined by Ken Thompson in Research Unix, inode contracts index node—a numbered entry in an on-disk index array that records every attribute of a filesystem object except its human-readable name and raw payload bytes. The stat system call contracts file status: it copies a normalized snapshot of a live VFS struct inode into user space. Linux classifies every VFS inode into seven mutually exclusive file types (ls -l prefix character) stored in bits [15:12] of the 16-bit POSIX mode_t st_mode word under mask S_IFMT (0170000), as illustrated in Figure 1.1a.
Figure 1.1a. 16-bit POSIX st_mode layout — bits [15:12] encode the seven VFS file types under S_IFMT (0170000) above the 12 special and rwx permission bits.
ls -l | VFS File Type | S_IFMT Octal Mask | POSIX Test Macro | Kernel Backing Resource |
|---|---|---|---|---|
- | Regular file | S_IFREG (0100000) | S_ISREG(m) | Disk or flash extents holding arbitrary bytes |
d | Directory | S_IFDIR (0040000) | S_ISDIR(m) | Name-to-inode [d_ino, d_name] mapping blocks |
c | Character device | S_IFCHR (0020000) | S_ISCHR(m) | Unbuffered driver file_operations (/dev/null) |
b | Block device | S_IFBLK (0060000) | S_ISBLK(m) | Random-access sector media (/dev/nvme0n1) |
l | Symbolic link | S_IFLNK (0120000) | S_ISLNK(m) | Separate inode storing a target pathname string |
p | FIFO (named pipe) | S_IFIFO (0010000) | S_ISFIFO(m) | In-memory kernel pipe ring buffer on VFS |
s | Socket | S_IFSOCK (0140000) | S_ISSOCK(m) | Local AF_UNIX endpoint bound to a VFS path |
Figure 1.1 and the step walkthrough below contrast how the three classic status system calls traverse paths and descriptors when populating struct stat.
- Step 1. Step 1: stat(pathname, &sb) resolves symlinks and copies the target inode's metadata into struct stat.
- Step 2. Step 2: lstat(pathname, &sb) stops at a symbolic link itself, reporting S_IFLNK (0120000) and link length.
- Step 3. Step 3: fstat(fd, &sb) queries an open descriptor's VFS inode directly without repeating path resolution.
- Step 4. Step 4: S_IS*(sb.st_mode) and struct timespec fields expose type, size, blocks, owner, and nanosecond times.
Figure 1.1b. Use lstat() when inspecting directory trees so symbolic links are never mistaken for their target inodes, and use fstat(fd) whenever a descriptor is already open.
Figure 1.1. Linux VFS inode resolution — path-following stat() versus symlink-aware lstat(), descriptor-anchored fstat(), S_IFMT masking, and statx().
One Layer Down: VFS Dentry Lookup, Bit Math & statx()
When user space calls stat(pathname, &sb), lstat(pathname, &sb) (link status), or fstat(fd, &sb) (file-descriptor status) after defining #define _XOPEN_SOURCE 700 and #define _FILE_OFFSET_BITS 64 above <sys/stat.h>, the Linux kernel enters vfs_fstatat() or vfs_fstat(). Path-based stat() walks the VFS directory-entry (dentry) cache with LOOKUP_FOLLOW, chasing up to MAXSYMLINKS (40) symbolic links before copying the final target's struct inode fields. By contrast, lstat() clears LOOKUP_FOLLOW on the final path component so a symlink returns its own S_IFLNK inode (st_size equals the target pathname byte length excluding '\0'). Descriptor-based fstat(fd, &sb) indexes current->files->fdt[fd]->f_inode in O(1) time with zero path re-lookup or rename race risk.
Examine the exact 16-bit octal arithmetic inside st_mode (where each octal digit represents 3 bits above the leading 0 radix prefix):
S_IFMT = 0170000(0xF000, binary1111_0000_0000_0000) isolates bits[15:12].S_IFSOCK = 0140000(0xC000),S_IFLNK = 0120000(0xA000), andS_IFREG = 0100000(0x8000). Evaluating unmasked0140000 & 0100000yields0100000 != 0, falsely classifying a socket as a regular file. Always evaluate(m & S_IFMT) == S_IFREG, which is exactly how<sys/stat.h>definesS_ISREG(m).- Inside
struct stat, pairingst_dev(mounted filesystem ID) withst_ino(partition-local inode number) forms the host-wide unique file key. Meanwhile,st_nlinkcounts hard links,st_uid/st_gidstore numeric owner/group IDs,st_rdevencodes major/minor driver numbers forc/bdevice nodes,st_blksizehints optimal I/O chunking (typically4096 B), andst_blockscounts allocated 512 B sectors (so a sparse1 MiBfile with one4 KiBwritten page reportsst_size == 1048576yetst_blocks == 8, consuming8 * 512 B = 4 KiBon disk).
On Linux 4.11+ (#define _GNU_SOURCE), statx() accepts an explicit stx_mask bitmask such as STATX_TYPE | STATX_MODE | STATX_SIZE so distributed or network filesystems skip computing unrequested attributes, verifies populated fields via stx.stx_mask, and exposes stx_btime file creation timestamps alongside AT_EMPTY_PATH descriptor queries. Furthermore, on 32-bit ARMv7 glibc 2.34+ targets, defining _FILE_OFFSET_BITS=64 and _TIME_BITS=64 widens time_t and struct timespec to 64 bits so timestamps never overflow signed INT32_MAX on 2038-01-19T03:14:07Z (Y2038).
Probing File Types, Mask-Scoped statx() & Y2038 Safety in C11
Save stat_types_probe.c below. On our Linux 6.12 host (sizeof(time_t) == 8 natively; add -D_TIME_BITS=64 alongside -D_FILE_OFFSET_BITS=64 when cross-compiling for 32-bit ARMv7), it creates a 64 B regular file, a directory, and a symbolic link, queries /dev/null, verifies S_IS* and S_IFMT masking, proves stat() and fstat() return identical st_ino values while lstat() isolates S_IFLNK, and validates mask-scoped statx().
learner@ksa:~/gl-c02/m01-l01$ bat -H 54 -H 57 -H 72 -H 74 stat_types_probe.c File: stat_types_probe.c #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> static char mode_type_char(mode_t m) { if (S_ISREG(m)) return '-'; if (S_ISDIR(m)) return 'd'; if (S_ISCHR(m)) return 'c'; if (S_ISBLK(m)) return 'b'; if (S_ISLNK(m)) return 'l'; if (S_ISFIFO(m)) return 'p'; if (S_ISSOCK(m)) return 's'; return '?'; } int main(void) { const char *reg_path = "/tmp/ksa_c02_l01.reg"; const char *dir_path = "/tmp/ksa_c02_l01.dir"; const char *lnk_path = "/tmp/ksa_c02_l01.lnk"; (void)unlink(lnk_path); (void)unlink(reg_path); (void)rmdir(dir_path); mode_t old_mask = umask(0022); int fd = open(reg_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0640); if (fd == -1 || mkdir(dir_path, 0755) == -1 || symlink(reg_path, lnk_path) == -1) { if (fd != -1) (void)close(fd); umask(old_mask); return EXIT_FAILURE; } uint8_t buf[64]; memset(buf, 0x5AU, sizeof(buf)); if (write(fd, buf, sizeof(buf)) != (ssize_t)sizeof(buf)) { (void)close(fd); umask(old_mask); return EXIT_FAILURE; } struct stat st_reg, st_fd, st_dir, st_lnk_self, st_lnk_follow, st_chr; struct statx sx; memset(&sx, 0, sizeof(sx)); unsigned int req = STATX_TYPE | STATX_MODE | STATX_SIZE; int sx_rc = statx(AT_FDCWD, reg_path, AT_SYMLINK_NOFOLLOW, req, &sx); int ok = (stat(reg_path, &st_reg) == 0 && fstat(fd, &st_fd) == 0 && stat(dir_path, &st_dir) == 0 && lstat(lnk_path, &st_lnk_self) == 0 && stat(lnk_path, &st_lnk_follow) == 0 && stat("/dev/null", &st_chr) == 0 && sx_rc == 0); (void)close(fd); (void)unlink(lnk_path); (void)unlink(reg_path); (void)rmdir(dir_path); umask(old_mask); if (!ok) return EXIT_FAILURE; int same_ino = (st_reg.st_ino == st_fd.st_ino && st_reg.st_ino == st_lnk_follow.st_ino && st_lnk_self.st_ino != st_reg.st_ino); int ifmt_ok = ((st_reg.st_mode & S_IFMT) == S_IFREG && (st_lnk_self.st_mode & S_IFMT) == S_IFLNK); int statx_ok = ((sx.stx_mask & STATX_SIZE) != 0U && sx.stx_size == 64ULL && sizeof(time_t) >= 8U); printf("types=%c%c%c%c follow_type=%c ifmt_ok=%d\n", mode_type_char(st_reg.st_mode), mode_type_char(st_dir.st_mode), mode_type_char(st_chr.st_mode), mode_type_char(st_lnk_self.st_mode), mode_type_char(st_lnk_follow.st_mode), ifmt_ok); printf("same_ino=%d size=%lld mode=0%03o rdev=%d statx_y2038=%d\n", same_ino, (long long)st_reg.st_size, (unsigned int)(st_reg.st_mode & 0777U), st_chr.st_rdev != 0, statx_ok); return EXIT_SUCCESS; }- Line 34.
O_CLOEXECprevents descriptor leaks across laterexecve()calls, while0640 & ~0022yields mode0640. - Line 54.
statx()requests onlySTATX_TYPE | STATX_MODE | STATX_SIZEwithAT_SYMLINK_NOFOLLOW, avoiding unneeded attribute fetches. - Line 57.
lstat()inspectslnk_pathwithout dereferencing, whereasstat()on line 58 follows it toreg_path's inode. - Line 72. Masking
(st_mode & S_IFMT)before comparingS_IFREGorS_IFLNKavoids multi-bit octal collisions.
Guided Practice
Before running ./stat_types_probe, trace lnk_path ("/tmp/ksa_c02_l01.lnk" -> "/tmp/ksa_c02_l01.reg", a 21-character target string) and predict two values:
- Cue 1 (
st_sizecontrast): What byte count doesst_lnk_follow.st_sizereport versusst_lnk_self.st_size? (*Hint:*stat()inspects the64 Bregular file, whereaslstat()reportsstrlen(reg_path)without a NUL terminator, which equals21.) - Cue 2 (Descriptor
statx): Complete the call that queriessxdirectly from open descriptorfdwithout re-walkingreg_path:statx(fd, "", /* flag? */, STATX_BASIC_STATS, &sx)-> supplyAT_EMPTY_PATHand verify(sx.stx_mask & STATX_INO) != 0U.
Independent Practice
Extend a local scratch copy of stat_types_probe.c without consulting the reference code above:
- Task: Create a named pipe (
mkfifo("/tmp/ksa_c02_l01.fifo", 0600)) and a dangling symlink (symlink("/tmp/does_not_exist", "/tmp/ksa_c02_l01.dangling")). Prove in code thatlstat()on the dangling link returns0withS_ISLNK(st.st_mode)non-zero whilestat()returns-1witherrno == ENOENT, and clean up both paths before exit. - Transfer Challenge: Suppose a distributed backup tool scans 10 million files over NFSv4 needing only file type and inode number, never file size or
mtime. How does switching fromlstat()tostatx(..., STATX_TYPE | STATX_INO, &sx)alter network RPC latency when remote writers hold active delegations?
Compiling and Verifying VFS Inode Metadata
Compile stat_types_probe.c under strict C11 flags on the Linux 6.12 host and verify that lstat() reports 'l' on the symbolic link, stat() dereferences it to '-' with the exact target st_ino, and statx() + 64-bit time_t succeed (statx_y2038=1).
learner@ksa:~/gl-c02/m01-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror stat_types_probe.c -o stat_types_probelearner@ksa:~/gl-c02/m01-l01./stat_types_probetypes=-dcl follow_type=- ifmt_ok=1same_ino=1 size=64 mode=0640 rdev=1 statx_y2038=1learner@ksa:~/gl-c02/m01-l01Why VFS Type Masks and lstat() Anchor Safe Tools
Running ./stat_types_probe confirmed how the Linux kernel decouples pathnames from inodes. Calling stat(lnk_path, &st_lnk_follow) traversed the symbolic link transparently and returned st_reg.st_ino (follow_type=-, same_ino=1), proving why S_ISLNK(st.st_mode) can never evaluate true on a stat() or fstat() result. Only lstat(lnk_path, &st_lnk_self) stopped at the link's own inode (types=-dcl, st_lnk_self.st_ino != st_reg.st_ino).
Notice also how /dev/null reported S_ISCHR with a non-zero kernel device ID st_rdev (rdev=1) despite occupying zero disk blocks, while statx() populated stx_size == 64 and confirmed sx.stx_mask & STATX_SIZE. Next, we examine how the kernel evaluates st_uid, st_gid, special permission bits (S_ISUID, S_ISGID, S_ISVTX), and nanosecond timestamp updates across real and effective credentials.
stat(2) Quick Reference
stat(2) GL-C02 Quick Reference stat(2) NAME stat, fstat, lstat, fstatat - query VFS inode metadata and st_mode SYNOPSIS #include <fcntl.h> /* AT_* constants */ #include <sys/stat.h> int stat(const char *pathname, struct stat *statbuf); int lstat(const char *pathname, struct stat *statbuf); int fstat(int fd, struct stat *statbuf); int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags); STANDARDS POSIX.1-2008; lstat() and fstatat() require _POSIX_C_SOURCE >= 200809L. RETURN VALUE Returns 0 and populates *statbuf on success, or -1 setting errno. ERRORS EACCES Search permission denied on a directory prefix of pathname. EBADF fd or dirfd is not a valid open file descriptor. ELOOP Too many symbolic links encountered while resolving pathname. ENOENT Component of pathname missing or dangling symlink (stat()). ENOTDIR A prefix component of pathname is not a directory. FLAGS AT_SYMLINK_NOFOLLOW Inspect symbolic link inode itself in fstatat(), like lstat(). AT_EMPTY_PATH Operate on dirfd when pathname is "" (requires _GNU_SOURCE). SEE ALSO access(2), chmod(2), openat(2), readlink(2), statx(2) Kernel Systems Academy Lesson 1.1 stat(2) GL-C02 quick reference · full manual page: man 2 stat Common Production Pitfalls
warning: Symptom: Writing if (st.st_mode & S_IFREG) to check for a regular file falsely matches sockets (S_IFSOCK = 0140000) and symbolic links (S_IFLNK = 0120000). Root Cause: S_IFMT file-type values are multi-bit octal codes (0140000 has the 0100000 bit set), not independent single-bit flags. Fix: Always mask with (st.st_mode & S_IFMT) == S_IFREG or invoke S_ISREG(st.st_mode).
warning: Symptom: A backup scanner calls stat(entry_path, &st) and checks if (S_ISLNK(st.st_mode)), silently following symlinks into infinite directory loops or failing with ENOENT on dangling links. Root Cause: stat() always dereferences symbolic links before populating struct stat. Fix: Call lstat() or fstatat(dfd, name, &st, AT_SYMLINK_NOFOLLOW) whenever auditing paths that could be symbolic links.
Knowledge Check
Key takeaways
GL-C02extendsGL-C01POSIX descriptors across VFS metadata, links, directory streams,/proctelemetry, asynchronous signals, processes, and threads.- Linux encodes seven VFS file types (
-,d,c,b,l,p,s) in bits[15:12]ofst_mode, tested safely via(st_mode & S_IFMT)orS_ISREG..S_ISSOCK. stat()dereferences symbolic links to their target,lstat()inspects the symbolic link inode itself, andfstat(fd)queries an already-open VFS inode inO(1)without path re-traversal.- Linux
statx()queries caller-maskedstx_maskattributes andstx_btimecreation timestamps, while_FILE_OFFSET_BITS=64and_TIME_BITS=64guarantee 64-bitoff_tand Y2038-safetime_ton 32-bit ARMv7.