Filesystems, Signals, Processes & Threads in C

For: Embedded Linux, systems, and infrastructure C engineers

Build production multi-process and multi-threaded Linux C11 software across symlink-safe directory trees, monotonic clocks, /proc telemetry, race-free POSIX signals, fork/execve supervisors, and synchronized pthreads.

18 lessons6 labs~13h 40mLinux 6.12C11glibc 2.39Course 2 of 4 · Intermediate

What you'll build

lab m0150 min

Symlink-Safe Directory Auditor & Atomic Manifest

Inspect Linux's seven VFS file types and struct stat inode fields via stat/fstat/lstat, manage UID/GID ownership, mode bits, special bits, and nanosecond utimensat/futimens timestamps without TOCTOU races, and build symlink-safe directory scanners with crash-atomic rename() updates.

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01./tree_auditor ./fixture manifest.txt && cat manifest.prevreg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42OLD_V0learner@ksa:~/gl-c02/lab-m01
lab m0250 min

Aligned /proc Telemetry Parser & CLI Filter

Replace overflow-prone C string and numeric routines with getline, snprintf, memmove, getopt, strtol, and POSIX Extended Regular Expressions, query host limits, monotonic clocks, EINTR-safe nanosleep, and getrandom(), and stream virtual /proc telemetry into cache-aligned heap structures.

learner@ksa: ~/gl-c02/lab-m02
learner@ksa:~/gl-c02/lab-m02./proc_telemetry -s status.mock -m meminfo.mock -l 0x1000align64=1 pid=4242 rss_kb=6144 threads=3 memtotal_kb=8192000 avail_kb=4096000 over_limit=1learner@ksa:~/gl-c02/lab-m02
lab m0355 min

Race-Free Realtime Signal Queue & sigsuspend Loop

Configure deterministic POSIX signal dispositions via sigaction() while respecting uncatchable SIGKILL/SIGSTOP, eliminate lost-wakeup races and handler deadlocks with sigprocmask(), sigsuspend(), volatile sig_atomic_t, and errno preservation, and transmit ordered payloads over SIGRTMIN+n queues with sigqueue() and SA_SIGINFO.

learner@ksa: ~/gl-c02/lab-m03
learner@ksa:~/gl-c02/lab-m03./rt_sigsupervisorpending_both=1 drained=5 order=101,102,103,501,502 prio_fifo_ok=1 errno_saved=1learner@ksa:~/gl-c02/lab-m03
lab m0455 min

Process Worker Supervisor, Reaper & Singleton Lock

Master ELF virtual memory segments, POSIX environment manipulation, Copy-on-Write fork() descriptor topologies, non-blocking SIGCHLD waitpid() reaping, execve() O_CLOEXEC hygiene, setsid() daemonization, advisory fcntl singleton locks, and the Linux IPC taxonomy.

learner@ksa: ~/gl-c02/lab-m04
learner@ksa:~/gl-c02/lab-m04./worker_supervisor supervise ./sup.pid 2SUPERVISOR attempts=3 crashes_reaped=2 cloexec_clean=1 final_status=0learner@ksa:~/gl-c02/lab-m04
lab m0555 min

Cancellable Thread Pool with TLS & sigwait

Spawn, join, and detach POSIX threads safely across disjoint slots, guard critical updates under deferred cancellation with LIFO cleanup handlers and right-sized stacks, and isolate per-thread state and signals using reentrant _r APIs, TSD destructors, _Thread_local, and synchronous sigwait().

learner@ksa: ~/gl-c02/lab-m05
learner@ksa:~/gl-c02/lab-m05./tls_sigwait_pool events.csv complete && ./tls_sigwait_pool events.csv cancelPOOL mode=complete workers=3 tokens=24 cleanups=3 tsd_dtors=3 canceled=0 sig=USR1POOL mode=cancel workers=3 batch1_tokens=12 cleanups=3 tsd_dtors=3 canceled=3 sig=TERMlearner@ksa:~/gl-c02/lab-m05
lab m0690 min

Concurrent Directory Indexer & sigwait Engine

Eliminate load-modify-store data races and AB-BA deadlocks with ordered pthread_mutex_t hierarchies, coordinate producer-consumer pipelines and read-heavy tables with monotonic condition variables, spinlocks, and read-write locks, and synthesize a crash-atomic multi-threaded directory indexer.

learner@ksa: ~/gl-c02/lab-m06
learner@ksa:~/gl-c02/lab-m06./concurrent_indexer --sigtest ./tree '\.(c|h|conf)$' ./index.manifest 4 && head -n 2 ./index.manifestINDEXER status=ok workers=4 matched=4 bytes=43 symlinks=1 dirs=5 visited=9 sigusr1=1 monotonic_ok=1SUMMARY matched_files=4 matched_bytes=43 symlinks_skipped=1 dirs_scanned=5 visited_entries=9EXT .c files=2 bytes=23learner@ksa:~/gl-c02/lab-m06

Syllabus

gl-c02/

  • m01/ Filesystem Metadata, Links & Directories

    Inspect Linux's seven VFS file types and struct stat inode fields via stat/fstat/lstat, manage UID/GID ownership, mode bits, special bits, and nanosecond utimensat/futimens timestamps without TOCTOU races, and build symlink-safe directory scanners with crash-atomic rename() updates.

    • 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().

    • Gatekeeping open() with access() creates exploitable TOCTOU privilege escalations, while forgetting VFS short-circuit owner rules or directory execute bits causes mysterious EACCES errors. You will evaluate real vs effective credentials, control umask, fchmod, and fchown safely, and update nanosecond timestamps via futimens() and utimensat().

    • Contrast hard links (link(), shared st_ino, EXDEV) against symbolic links (symlink(), bounded readlink(), dangling paths). Traverse directories with opendir/readdir (getdents64 batching, DT_UNKNOWN -> fstatat fallback, (st_dev, st_ino) guards). Implement open-then-unlink scratch files and crash-atomic file replacement via sibling staging and rename().

  • m02/ Bounded Strings, Clocks, Heap & /proc

    Replace overflow-prone C string and numeric routines with getline, snprintf, memmove, getopt, strtol, and POSIX Extended Regular Expressions, query host limits, monotonic clocks, EINTR-safe nanosleep, and getrandom(), and stream virtual /proc telemetry into cache-aligned heap structures.

    • Format and slice C strings safely with getline(), snprintf() truncation checks, memmove(), and struct node **indir lists. Parse CLI flags via POSIX getopt() paired with errno- and endptr-validated strtol(), strtoul(), and strtod(). Execute and free POSIX Extended Regular Expressions (<regex.h>) using regcomp(REG_EXTENDED), regmatch_t offsets, and regfree().

    • Query kernel identity, RAM scale, and runtime limits via uname(), sysinfo(), and sysconf(_SC_PAGESIZE, _SC_NPROCESSORS_ONLN). Convert UTC Epoch and timezone calendars reentrantly via clock_gettime(CLOCK_REALTIME), gmtime_r(), localtime_r(), and strftime(). Benchmark intervals on CLOCK_MONOTONIC (warm-up, DCE barrier, median/p99), resume EINTR nanosleep(), and call getrandom().

    • Allocate heap buffers safely via overflow-checked calloc(), temp-pointer realloc(), free(), and -fsanitize=address redzones. Inspect struct alignment (_Alignof, _Static_assert), posix_memalign() / aligned_alloc(), and glibc M_MMAP_THRESHOLD arenas. Stream dynamic Linux /proc seq_file pseudo-files (/proc/self/status, /proc/meminfo) sequentially despite st_size == 0.

  • m03/ POSIX Signals, Masks & Realtime Queues

    Configure deterministic POSIX signal dispositions via sigaction() while respecting uncatchable SIGKILL/SIGSTOP, eliminate lost-wakeup races and handler deadlocks with sigprocmask(), sigsuspend(), volatile sig_atomic_t, and errno preservation, and transmit ordered payloads over SIGRTMIN+n queues with sigqueue() and SA_SIGINFO.

    • Classify synchronous CPU faults (ucontext_t, rt_sigreturn) vs async signals, default dispositions, and 1..31 vs SIGRTMIN ranges. Dispatch signals and probe process liveness and permissions using getpid(), kill(pid, sig), raise(sig), and kill(pid, 0). Install race-free dispositions via struct sigaction (sa_mask, SA_RESTART, SA_ONSTACK) and verify EINVAL on SIGKILL/SIGSTOP.

    • Construct signal sets (sigemptyset..sigismember) and guard critical sections via sigprocmask(SIG_BLOCK / SIG_SETMASK). Eliminate unblock-then-sleep races using atomic sigsuspend(&mask) and pollable signalfd(SFD_NONBLOCK | SFD_CLOEXEC) descriptors. Author async-signal-safe handlers using volatile sig_atomic_t and saved errno without non-reentrant printf/malloc deadlocks.

    • Snapshot blocked pending signals via sigpending() and address POSIX realtime signals dynamically as SIGRTMIN + n (<= SIGRTMAX). Transmit queued union sigval events via sigqueue() and inspect si_pid, si_uid, and si_value inside SA_SIGINFO handlers. Verify SIGRTMIN priority and FIFO ordering under sigsuspend(), and contrast unconditional abort() against normal exit.

  • m04/ Process Lifecycle, exec, Daemons & IPC Map

    Master ELF virtual memory segments, POSIX environment manipulation, Copy-on-Write fork() descriptor topologies, non-blocking SIGCHLD waitpid() reaping, execve() O_CLOEXEC hygiene, setsid() daemonization, advisory fcntl singleton locks, and the Linux IPC taxonomy.

    • Map ELF segments, demand-paged minor/major faults (getrusage), and RSS vs PSS (/proc/self/smaps_rollup) across virtual memory. Manipulate the POSIX environment vector safely via getenv(), setenv(), unsetenv(), and clearenv() without putenv() stack bugs. Control fork() Copy-on-Write PTE sharing, O(PTE) scaling, shared struct file cursors, and fflush(NULL) stdio buffer hygiene.

    • Contrast user-space exit() (atexit LIFO hooks + stdio flush) against immediate kernel _exit() / _Exit() in forked children. Reap Z-state zombies under coalesced SIGCHLD bursts via while (waitpid(-1, &st, WNOHANG) > 0) loops and race-free pidfd_open(). Launch programs cleanly with execve() / posix_spawn() and O_CLOEXEC hygiene while avoiding threaded-fork() lock poisoning.

    • Diagnose Linux task states (R, S, D, T, Z), process groups (PGID), and controlling-terminal sessions (SID / SIGHUP). Execute canonical setsid() daemon detachment and enforce crash-safe singleton execution via advisory fcntl(F_SETLK) record locks. Classify the Linux IPC taxonomy across pipes/FIFOs/signals, System V and POSIX message queues/semaphores/shm, and BSD sockets.

  • m05/ POSIX Threads, Cancellation & Thread Safety

    Spawn, join, and detach POSIX threads safely across disjoint slots, guard critical updates under deferred cancellation with LIFO cleanup handlers and right-sized stacks, and isolate per-thread state and signals using reentrant _r APIs, TSD destructors, _Thread_local, and synchronous sigwait().

    • Distinguish NPTL 1:1 clone() sharing flags, process TGID (getpid()) vs kernel TID (gettid()), and opaque pthread_self(). Spawn worker threads with -pthread and pthread_create() using dedicated per-worker struct slots and direct return-code checks. Harvest worker results via pthread_join() or enable automatic reclamation via pthread_detach() without stack-pointer hazards.

    • Control cooperative termination via pthread_cancel(), PTHREAD_CANCEL_DISABLE guards, cancellation points, and pthread_testcancel(). Unwind per-thread resources deterministically in LIFO order using lexically paired pthread_cleanup_push() and pthread_cleanup_pop(). Configure pthread_attr_t stack/guard sizes (PROT_NONE guard pages) while avoiding silent guard disablement in pthread_attr_setstack().

    • Separate Reentrant (_r), MT-Safe, and Async-Signal-Safe routines to prevent static-buffer corruption and handler self-deadlocks. Isolate per-thread state using C11 _Thread_local (.tdata/.tbss CPU thread register) paired with pthread_key_create() destructors. Implement multi-threaded signal handling by blocking signals via pthread_sigmask() before pthread_create() and dedicating sigwait().

  • m06/ Thread Synchronization & Concurrent Capstone

    Eliminate load-modify-store data races and AB-BA deadlocks with ordered pthread_mutex_t hierarchies, coordinate producer-consumer pipelines and read-heavy tables with monotonic condition variables, spinlocks, and read-write locks, and synthesize a crash-atomic multi-threaded directory indexer.

    • Diagnose 64-byte MESI false sharing (_Alignas(64)), C11 <stdatomic.h> acquire/release ordering, and volatile non-atomicity. Configure pthread_mutex_t (ERRORCHECK, PTHREAD_PRIO_INHERIT) and trace its 3-state user-space futex 0-syscall fastpath. Prevent single-lock self-deadlocks and multi-lock AB-BA lock-inversion deadlocks by enforcing strict global lock ordering.

    • Coordinate producer-consumer queues via pthread_cond_t, while (!pred) loops, broadcast/signal wakeups, and CLOCK_MONOTONIC waits. Evaluate spinlock coherence (TAS, TTAS, ticket, MCS) vs mutex sleeping and diagnose oversubscribed lock-holder preemption. Scale read-heavy tables with pthread_rwlock_t while mitigating shared reader-count cache bouncing and writer starvation.

    • Design a deadlock-free directory crawler combining pthread_mutex_t, pthread_cond_t, in_flight tracking, and intrusive list_head. Integrate lstat() loop guards, MT-Safe <regex.h> filters, _Thread_local counters, and stack-safe iterative merge sort. Coordinate synchronous sigwait() shutdown, CLOCK_MONOTONIC telemetry, and crash-atomic fdatasync() + rename() output.

Prerequisites

  • requiredGL-C01 (or equivalent): POSIX open/read/write/lseek/close, VFS file tables, buffered stdio, and errno
  • requiredStrict C11 compilation workflow on Linux (gcc -std=c11 -Wall -Wextra -Werror and GNU Make)
  • Bridged in M1GL-C01 VFS descriptor & errno recap plus 16-bit st_mode bitmask layout (Module 1, Lesson 1)
  • Bridged in M1Directory-relative *at() nanosecond metadata calls vs legacy utime/stime (Module 1, Lesson 2)
  • Bridged in M3Async-signal-safe handler rules (man 7 signal-safety) before sigaction & sigsuspend (Module 3, Lesson 2)
  • Bridged in M5–M6GCC -pthread build contract, reentrancy vs MT-Safe taxonomy, and lock-ordering rules (Modules 5–6)

Series map

  1. GL-C01Syscalls, File Tables & Buffering — Kernel boundary, glibc, GCC/Make, POSIX file I/O, VFS open-file tables, atomic I/O, stdio & durability
  2. GL-C02Filesystems, Signals, Processes & Threads — stat/inodes, directory traversal, system info/time, POSIX signals, fork/exec/wait, daemons & pthreads this course
  3. GL-C03Advanced I/O, IPC & Network Sockets — Nonblocking I/O, poll/epoll, mmap, record locks, pipes/FIFOs/SysV IPC & TCP/UDP socket servers
  4. GL-C04Embedded Linux Peripherals, Display, Video & Audio — Sysfs GPIO/LED/PWM, evdev input, RTC/I2C/SPI/UART, Framebuffer/DRM, V4L2 camera & ALSA audio

Related live cohorts: KRN-101 · Linux Systems & Kernel Foundations (live cohort) RTL-101 · Real-Time Linux with PREEMPT_RT (live cohort)

Companion formats

Slide deck

16:9 review slides with terminal listings, diagrams, and speaker notes.

Reference handbook

Printable HTML and PDF engineering reference covering every module and UAPI.

Flashcards

Leitner spaced-repetition terminal cards and TSV deck for syscalls, flags, and pitfalls.

Kernel Systems Academy engineering studio

Every Kernel Systems Academy course follows our 35% principles / 20% guided investigation / 45% engineering studio pedagogy. Listings are compiled against Linux 6.12 · C11 · glibc 2.39 under strict compiler flags (-Wall -Wextra -Werror), and each module culminates in an evidence-checked lab graded locally by ./check.sh.

Frequently asked questions

Can I study this course offline from disk?

Yes. All fonts, stylesheets, diagrams, search indexes, and progress trackers use relative paths and local browser storage, so the bundle works identically over HTTP and file://.

How are the hands-on labs graded?

Each lab directory includes starter source files and an executable ./check.sh runner emitting TAP version 13 diagnostics (ok / not ok) and exiting 0 when every check passes.

What is included in the free preview?

Preview lessons and the opening module lab are unlocked in full so you can inspect our C11 listings, strace transcripts, and ./check.sh workflow before subscribing.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure