How gd-arnold/tiny-nginx works
Project type and purpose
• This is a lightweight, event-driven HTTP server written in C, inspired by Nginx.
• It uses a multi-process model with non-blocking I/O (epoll) and serves static files.
File structure
• Top-level:
• public/ (static content served)
• src/ (all C source and headers)
• Makefile, README.md, images/
• In src/:
• main.c – program entry point
• master.{c,h} – initializes listener, spawns worker processes, handles signals
• worker.{c,h} – per-CPU worker process logic
• server.{c,h} – sets up shared listening socket
• client.{c,h} – HTTP client state machine
• event.{c,h} – epoll wrapper and event dispatch
• dbg.h – logging/debug macros
Supplementary insights from README
• Key patterns: non-blocking epoll loop, state-machine for HTTP, sendfile() for zero-copy file serving
• Constraints: Linux only (epoll), static file serving from ./public
Main components
a. Master Process
• Responsibilities: create listening socket, fork workers, handle shutdown
• Uses: socket(), bind(), listen(), fork(), signal handlers
b. Shared Listening Socket
• Single socket descriptor inherited by all workers
c. Worker Processes (Worker 1 … Worker N)
• Each bound to one CPU core via CPU affinity
• Run an event loop based on epoll_wait()
• Handle SERVER_EVENT (accept), CLIENT_EVENT (read/write), SIGNAL_EVENT
d. Event System
• epoll instance per worker, tracks file descriptors for listening socket, client sockets, signal pipe
e. HTTP Client State Machine
• States: RECEIVING_REQUEST, SENDING_HEADERS, SENDING_FILE, CLOSING
f. Static File Storage
• public/ directory on disk accessed via sendfile()
g. External interfaces
• TCP/IP network (port, client connections)
• OS kernel for epoll and sendfile
Relationships and interactions
• Master → forks → Worker processes
• All Workers → inherit → Listening Socket
• Worker Event Loop ↔ Listening Socket (accept new connections)
• Worker Event Loop ↔ Client Sockets (I/O events)
• Client Socket processing → reads request, resolves path under public/, uses sendfile() → file descriptor → client
• Signal events in master and workers for graceful shutdown
Architectural patterns and design principles
• Multi-process concurrency: isolates worker faults, leverages multiple CPU cores
• Event-driven, non-blocking I/O: scalable connection handling via epoll
• Zero-copy I/O: sendfile() to minimize user→kernel data copies
• State machine for HTTP: clear separation of request, header, body, and teardown phases
Relevant technologies/frameworks/libraries
• C standard library and POSIX APIs (socket, fork, epoll, sendfile)
• Linux-specific features (epoll, CPU affinity)
Detail
• That each worker binds to a CPU core (annotate “CPU #” next to each worker)
• Signal handling path for graceful shutdown, both in master and workers