Advanced I/O, IPC, Sockets, CMake & MQTT in C

For: Embedded Linux, systems, and network infrastructure C engineers

Architect high-concurrency nonblocking Linux C11 network daemons, shared-memory IPC pipelines, multi-directory CMake builds, and wire-level MQTT 3.1.1 telemetry clients.

18 lessons6 labs~12h 30mLinux 6.12C11glibc 2.39Course 3 of 4 · Intermediate–Advanced

What you'll build

lab m0155 min

Edge-Triggered Epoll Pipe & Eventfd Reactor

Transition file descriptors into nonblocking mode (O_NONBLOCK), compare O(N) select() and poll() readiness scans, and build scalable O(1)-ready epoll_create1/EPOLLET/eventfd event loops.

learner@ksa: ~/gl-c03/lab-m01
learner@ksa:~/gl-c03/lab-m01./files/epoll_reactor 25channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87 stop_evfd=1learner@ksa:~/gl-c03/lab-m01
lab m0255 min

POSIX Shared-Memory Ring & Byte-Range Audit Ledger

Map files into process virtual memory with mmap() and msync(), coordinate concurrent writers with fcntl() byte-range record locks and flock(), and build local IPC pipelines over pipe2(), mkfifo(), and POSIX shm_open() shared memory.

learner@ksa: ~/gl-c03/lab-m02
learner@ksa:~/gl-c03/lab-m02./files/shm_lock_ring 24 ledger24.binrecords=24 ring_wraps=3 ledger_bytes=400 digest=0x8702e998 shm_clean=1learner@ksa:~/gl-c03/lab-m02
lab m0355 min

IPv4/TCP Wire Decoder, Pseudo-Header Checksum & Handshake Validator

Trace packet encapsulation across OSI and TCP/IP layers, manipulate IPv4/IPv6 CIDR subnets and network byte order cleanly, and decode 20-byte TCP headers, RFC 1071 pseudo-header checksums, and 3-way/4-way connection state transitions.

learner@ksa: ~/gl-c03/lab-m03
learner@ksa:~/gl-c03/lab-m03./files/tcp_wire_inspector 1000 5000 PING_GL_C03segs=8 syn_csum=0xb2a4 csum_ok=1 tamper_caught=1 cli_next=1013 srv_next=5002 state=5learner@ksa:~/gl-c03/lab-m03
lab m0460 min

Single-Thread Nonblocking Epoll Framed KV Server

Build length-prefixed SOCK_STREAM TCP clients/servers, boundary-preserving SOCK_DGRAM UDP endpoints with reentrant getaddrinfo(), and single-thread nonblocking epoll network daemons.

learner@ksa: ~/gl-c03/lab-m04
learner@ksa:~/gl-c03/lab-m04./epoll_kv_server kv.port  # SET/GET/QUIT framed sessionSET sensor_node edge_active_42 -> OKGET sensor_node -> VALUE edge_active_42QUIT -> BYElearner@ksa:~/gl-c03/lab-m04
lab m0555 min

Multi-Target Out-of-Source CMake Network Buffer SDK

Author out-of-source ISO C11 CMake build graphs, propagate PRIVATE/PUBLIC/INTERFACE usage requirements, generate headers via configure_file(), and cross-compile multi-directory trees with toolchain files.

learner@ksa: ~/gl-c03/lab-m05
learner@ksa:~/gl-c03/lab-m05./build/netbuf_clinetbuf_sdk: ver=2.4.0 bounds=1 len=10 hex=0102000003E84F4B6733 overflow_rc=-1learner@ksa:~/gl-c03/lab-m05
lab m0690 min

CMake Nonblocking Epoll MQTT 3.1.1 Telemetry & Command Client

Encode and decode OASIS MQTT 3.1.1 binary control packets, implement QoS 0/1/2, Retained, LWT, and KeepAlive state machines, and integrate CMake + nonblocking epoll into a deterministic MQTT client.

learner@ksa: ~/gl-c03/lab-m06
learner@ksa:~/gl-c03/lab-m06./build/mqtt_client_app 127.0.0.1 41099 gw07MQTT_CLIENT connack=0 suback=1 puback_id=2 telem_bytes=141 pingresp=1 cmd=VALVE=OPEN disconnect=1learner@ksa:~/gl-c03/lab-m06

Syllabus

gl-c03/

  • m01/ Nonblocking I/O & Event Multiplexing

    Transition file descriptors into nonblocking mode (O_NONBLOCK), compare O(N) select() and poll() readiness scans, and build scalable O(1)-ready epoll_create1/EPOLLET/eventfd event loops.

    • Welcome to Course 3 (GL-C03) in the Linux Systems Programming in C11 track. Building on GL-C01 open-file descriptions and GL-C02 process, signal, and thread primitives, you will contrast TASK_INTERRUPTIBLE wait-queue sleep against O_NONBLOCK status flags, handle EAGAIN and EWOULDBLOCK safely, and quantify why unthrottled polling loops waste 100% of a CPU core.

    • Unthrottled O_NONBLOCK loops burn 100% CPU while blocking read() stalls on the first quiet stream. You will multiplex nonblocking channels at 0% idle CPU with select() and poll(), contrast destructive 1024-bit fd_set bitmasks against reusable struct pollfd arrays, prevent FD_SETSIZE stack overflows, and quantify stateless O(N) kernel scan costs.

    • Evaluate O_ASYNC/F_SETSIG signal-driven I/O hazards, epoll readiness, and Linux 6.12 io_uring SQ/CQ rings. Register descriptors in epoll O(log N) red-black trees (epoll_ctl) and harvest O(1) events via epoll_wait(). Write EPOLLET O_NONBLOCK drain-to-EAGAIN loops with eventfd() shutdown wakeups and EPOLLONESHOT safety.

  • m02/ Memory Mapping, Record Locks & Local IPC

    Map files into process virtual memory with mmap() and msync(), coordinate concurrent writers with fcntl() byte-range record locks and flock(), and build local IPC pipelines over pipe2(), mkfifo(), and POSIX shm_open() shared memory.

    • Call mmap() at sysconf(_SC_PAGESIZE) alignment over pre-sized files while checking MAP_FAILED ((void *)-1). Compare MAP_SHARED page-cache write-through (msync(MS_SYNC)) against MAP_PRIVATE Copy-on-Write isolation. Diagnose SIGBUS past-EOF backing faults versus SIGSEGV PROT_* permission faults and apply madvise() hints.

    • Contrast cooperative advisory locking on Linux against deprecated System V mandatory locking (S_ISGID mode bits). Use whole-file BSD flock(LOCK_SH | LOCK_EX | LOCK_NB) locks bound to struct file across dup() and fork(). Implement byte-range POSIX fcntl(F_SETLK) and Linux F_OFD_SETLK (l_pid = 0) locks without close() lock loss.

    • Build pipe2(O_CLOEXEC) byte streams using <= PIPE_BUF (4096 B) atomic writes and strict unused-fd close() discipline. Configure mkfifo() S_IFIFO rendezvous nodes enabling unrelated local processes to stream through kernel RAM. Construct zero-copy shm_open and memfd_create (F_ADD_SEALS) MAP_SHARED rings synchronized with sem_t.

  • m03/ Network Architecture, IP Addressing & TCP Wire

    Trace packet encapsulation across OSI and TCP/IP layers, manipulate IPv4/IPv6 CIDR subnets and network byte order cleanly, and decode 20-byte TCP headers, RFC 1071 pseudo-header checksums, and 3-way/4-way connection state transitions.

    • Differentiate Layer-2 48-bit MAC LAN frame switching from Layer-3 IP routing that rewrites link headers per hop. Trace TCP/UDP segment, IPv4/IPv6 packet, and 14-byte Ethernet II encapsulation yielding MSS = 1460 at MTU = 1500. Apply <arpa/inet.h> htons(), htonl(), ntohs(), and ntohl() conversions with alignment-safe memcpy() loads.

    • Implement UB-free CIDR /prefix subnet (ip & mask), broadcast (subnet | ~mask), and RFC 1918 checks in C11. Inspect 16-bit big-endian transport ports across privileged (0..1023), registered (1024..49151), and ephemeral ranges. Write reentrant inet_pton()/inet_ntop() converters populating zeroed sockaddr_in, sockaddr_in6, and sockaddr_storage.

    • Compare boundary-preserving 8-byte UDP datagrams against unstructured 20..60-byte TCP byte streams requiring framing. Validate 20-byte TCP headers (seq, ack, data_offset, flags, window) and 12-byte IPv4 pseudo-header checksums. Analyze 3-way SYN handshakes, 4-way CLOSE_WAIT/TIME_WAIT teardowns, dual listen queues, and TCP_NODELAY.

  • m04/ POSIX Sockets & Nonblocking Network Servers

    Build length-prefixed SOCK_STREAM TCP clients/servers, boundary-preserving SOCK_DGRAM UDP endpoints with reentrant getaddrinfo(), and single-thread nonblocking epoll network daemons.

    • Configure SOCK_STREAM | SOCK_CLOEXEC listeners with SO_REUSEADDR and SO_REUSEPORT before bind() and listen(). Execute collision-free loopback socket tests by binding 127.0.0.1 port htons(0) and querying getsockname(). Build [uint32_t be_len][payload] TCP framing using scatter-gather writev(), recv_exact(), and shutdown(SHUT_WR).

    • Use SOCK_DGRAM sendto()/recvfrom() to preserve 1-to-1 datagram boundaries and connected UDP to surface ECONNREFUSED. Diagnose truncated UDP packets via MSG_TRUNC, bound blocking reads via SO_RCVTIMEO, and batch recvmmsg(). Implement dual-stack getaddrinfo()/freeaddrinfo() endpoint resolution alongside AF_UNIX socketpair() IPC.

    • Design single-thread nonblocking epoll TCP servers draining accept4(..., SOCK_NONBLOCK | SOCK_CLOEXEC) to EAGAIN. Write per-connection inbuf state machines reassembling split 4-byte headers and bursts with timerfd_create() eviction. Configure MSG_NOSIGNAL, on-demand EPOLLOUT backpressure arming, and zero-copy sendfile() payload delivery.

  • m05/ Modern CMake Build Systems & Cross-Toolchains

    Author out-of-source ISO C11 CMake build graphs, propagate PRIVATE/PUBLIC/INTERFACE usage requirements, generate headers via configure_file(), and cross-compile multi-directory trees with toolchain files.

    • Execute out-of-source CMake workflows (cmake -S . -B build) with -MMD -MP header tracking and compile_commands.json. Configure cmake_minimum_required(VERSION 3.16) and project(... LANGUAGES C) to lock policies and skip C++ probes. Build STATIC .a archives, -fPIC SHARED .so libraries (OUTPUT_NAME), and sanitizer builds in PROJECT_BINARY_DIR.

    • Apply PRIVATE, PUBLIC, and INTERFACE target usage requirements cleanly across target_link_libraries() DAG edges. Configure strict ISO C11 (-std=c11) compilation with CMAKE_C_STANDARD 11, STANDARD_REQUIRED ON, and EXTENSIONS OFF. Select persistent option() cache flags in CMakeCache.txt versus lexical function() variables with PARENT_SCOPE.

    • Construct multi-directory C11 build graphs with add_subdirectory(), isolating child scopes while linking targets globally. Write configure_file(... @ONLY) rules emitting build metadata headers cleanly into CMAKE_CURRENT_BINARY_DIR. Validate SOVERSION cmake --install staging trees and CMAKE_TOOLCHAIN_FILE sysroot isolation (Tag_ABI_VFP_args).

  • m06/ MQTT 3.1.1 Wire Protocol & Telemetry Capstone

    Encode and decode OASIS MQTT 3.1.1 binary control packets, implement QoS 0/1/2, Retained, LWT, and KeepAlive state machines, and integrate CMake + nonblocking epoll into a deterministic MQTT client.

    • Analyze brokered OASIS MQTT 3.1.1 publish/subscribe decoupling across space, time, and synchronization. Validate UTF-8 / topic hierarchies, + and # subscription filters, and $SYS/# broker-internal topic isolation. Implement MQTT [Type | Flags] Fixed Headers (0x82 SUBSCRIBE), X-macro tables, and 21-bit-safe base-128 varints.

    • Trace MQTT QoS 0, QoS 1 (PUBACK, DUP=1), and QoS 2 (PUBREC/PUBREL/PUBCOMP) under min(pub_qos, sub_qos). Configure RETAIN=1 last-known-good broker state caches and clear stale retained entries via zero-byte retained payloads. Diagnose Last Will & Testament (LWT) triggers across 1.5 * KeepAlive PINGREQ/PINGRESP timeouts vs DISCONNECT (0xE0).

    • Design a single-thread C11 MQTT client combining SOCK_NONBLOCK, EINPROGRESS + SO_ERROR, and epoll_create1(). Implement inbuf peek_pkt() extraction loops handling both split base-128 headers and coalesced broker packet bursts. Validate CMake nonblocking MSG_NOSIGNAL/EPOLLOUT MQTT telemetry and command flows against a 127.0.0.1:0 mock broker.

Prerequisites

  • requiredGL-C01 & GL-C02 (or equivalent): POSIX file descriptors, signals, fork/waitpid, and pthreads synchronization
  • requiredC11 compilation on Linux (gcc -std=c11 -Wall -Wextra -Werror, GNU Make, and basic shell tooling)
  • Bridged in M1GL-C01/GL-C02 VFS status-flag & signal recap before nonblocking I/O and epoll (Module 1)
  • Bridged in M2POSIX pipe2, mkfifo & shm_open shared-memory bridge alongside mmap & fcntl locks (Module 2)
  • Bridged in M4Reentrant getaddrinfo() & stream length-prefix framing over raw byte streams (Module 4)
  • Bridged in M6Loopback OASIS MQTT 3.1.1 binary packet broker harness with zero external cloud dependencies (Module 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
  3. GL-C03Advanced I/O, IPC, Sockets, CMake & MQTT — Nonblocking I/O, select/poll/epoll, mmap, record locks, pipes/shm, TCP/UDP sockets, CMake & MQTT this course
  4. GL-C04Embedded Linux Peripherals, Display, Video & Audio — Sysfs GPIO/LED/PWM, evdev input, RTC/UART/Watchdog, Framebuffer/JPEG/PNG/FreeType, V4L2, ALSA & SocketCAN

Related live cohorts: NET-101 · Linux Networking Stack Internals (live cohort) EMB-100 · Embedded Linux: Toolchain to Product (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