Skip to content

Linux System Programming

Write C that talks directly to the Linux kernel.

Learn how Linux really works by programming against it in C. Starting from pointers and the build toolchain, you work through system calls, file I/O, processes, signals, IPC, threads, virtual memory and sockets, then finish by building a mini shell and a concurrent TCP chat server that runs as a systemd service.

01C for systems programming

The C you need to read and write real Linux code.

  1. Pointers, arrays & memory layoutA pointer is a variable that holds a memory address, and nearly every Linux API passes data through pointers to buffers and structs. C gives you manual control over where data lives: on the stack, on the heap with malloc, or in static storage. Understanding this layout is the foundation for every bug you will debug later.11 min
  2. Structs, strings & bit manipulationStructs group related fields, and Linux APIs use them everywhere, from struct stat to struct sockaddr_in. C strings are just char arrays ending in a zero byte, so length and buffer size must be tracked by hand. Bit flags packed into integers are how system calls accept options like O_CREAT | O_TRUNC.10 min
  3. Building with gcc, make & librariesgcc turns C source into an executable in four stages: preprocessing, compiling, assembling and linking. make rebuilds only what changed, based on file timestamps and dependency rules. Knowing how linking works explains errors like undefined reference and why shared libraries must be found at run time.10 min
  4. Debugging with gdb, valgrind & sanitizersC has no runtime checks, so memory errors often corrupt data silently or crash far from the real bug. gdb lets you stop a program and inspect its state, valgrind memcheck detects leaks and invalid accesses, and AddressSanitizer compiles checks directly into your binary. Using them routinely turns hours of guessing into minutes.10 min

02The kernel/user boundary

How programs ask the kernel to do work on their behalf.

  1. User space, kernel space & hardwareThe CPU runs user programs in an unprivileged mode and the kernel in a privileged mode. Only the kernel can touch hardware, manage memory mappings or schedule processes, so user programs must ask it through system calls. The C library (glibc) wraps those calls in ordinary functions like open and read.10 min
  2. System calls & error handlingA system call switches the CPU from user mode into the kernel, runs a kernel function and returns a result. Most calls return -1 on failure and set the thread-local errno to explain why. Robust programs check every return value and handle cases like EINTR and short reads.9 min
  3. Tracing programs with strace & ltracestrace uses the ptrace facility to show every system call a program makes, with arguments and return values. Because all interaction with files, the network and other processes goes through syscalls, strace answers questions like which config file was opened or why a connect failed, even without source code. ltrace does the same for shared-library calls.9 min

03Files, I/O & file systems

Everything is a file: descriptors, buffering, inodes and the VFS.

  1. File descriptors: open, read, write, closeA file descriptor is a small integer that refers to an open file, pipe, socket or device in the kernel. open returns one, read and write move bytes through it, and close releases it. Because the same calls work for every kind of descriptor, this is the core of the everything-is-a-file design.13 min
  2. stdio buffering vs raw system callsstdio functions like printf and fgets keep a user-space buffer and only call write or read when it fills or is flushed. This cuts the number of expensive system calls dramatically. The trade-off is that buffered data can appear late, out of order with raw writes, or be lost if the process crashes or calls _exit.12 min
  3. lseek, dup2, fcntl & open flagsBeyond read and write, a few calls give you full control over descriptors. lseek moves the file offset, dup2 makes one descriptor number refer to another open file, which is exactly how shells redirect output, and fcntl reads or changes descriptor flags such as O_NONBLOCK and FD_CLOEXEC.13 min
  4. Inodes, hard links & symbolic linksAn inode stores a file's metadata and the location of its data, but not its name. Directories are tables that map names to inode numbers, so one inode can have several names, called hard links. A symbolic link is a separate small file whose content is a path to follow.12 min
  5. The VFS, mounts, /proc & /sysThe Virtual File System (VFS) gives every file system the same interface, so open and read work identically on ext4, xfs, NFS or tmpfs. Mounting attaches a file system to a directory in the single directory tree. Pseudo file systems like /proc and /sys expose live kernel data as files you can read with cat.11 min
  6. Directories, permissions & umaskDirectories are special files you read with opendir and readdir. Every file has an owner, a group and nine permission bits: read, write and execute for user, group and others. The process umask clears bits from the mode you request, so open with 0666 usually produces a 0644 file.12 min

04Processes

Create, replace, wait for and organise processes.

  1. Process anatomy & process statesA process is a running program plus everything the kernel tracks for it: an address space, open descriptors, credentials, signal state and one or more threads. The scheduler moves each task between states such as running, sleeping and stopped. ps and /proc show these states as letters like R, S, D, T and Z.12 min
  2. fork, exec & waitUnix creates processes in two steps: fork clones the calling process, and exec replaces the clone's program with a new one. The parent then calls wait or waitpid to block until the child ends and to collect its exit status. Every command you type in a shell runs through this pattern.12 min
  3. Exit, zombies, orphans & the environmentWhen a process exits, the kernel keeps a small record of its exit status until the parent collects it with wait; until then the child is a zombie. If the parent dies first, the child becomes an orphan and is adopted by PID 1 or a designated subreaper, which reaps it. Each process also inherits an environment of KEY=value strings from its parent.11 min
  4. Process groups, sessions & job controlProcesses are grouped for job control: every pipeline a shell launches gets its own process group, and all groups started from one terminal belong to one session. The terminal sends signals such as SIGINT from Ctrl-C to the whole foreground group. This is how a shell can stop, resume or kill an entire pipeline at once.11 min

05Signals

Asynchronous notifications and how to handle them safely.

  1. Signals & default actionsA signal is a small asynchronous notification sent to a process by the kernel, another process or the terminal. Each signal has a default action, such as terminating, dumping core, stopping or being ignored. Programs can catch most signals, but SIGKILL and SIGSTOP always take effect.11 min
  2. sigaction, masks & async-signal safetysigaction installs a signal handler with well-defined behaviour, unlike the older signal function. A handler can interrupt your code anywhere, so it must only call async-signal-safe functions and usually just sets a flag. Signal masks let you block delivery during critical sections.12 min
  3. Self-pipe trick & signalfdHandlers are awkward in programs built around an event loop. The self-pipe trick has the handler write one byte to a pipe that the loop watches, and Linux's signalfd goes further by letting you read signals from a descriptor. Either way, signals become ordinary events handled in normal code.11 min

06Inter-process communication

Move data and coordinate between separate processes.

  1. Pipes & FIFOsA pipe is a one-way kernel buffer with a read end and a write end, created with pipe and usually shared with a child through fork. A FIFO is the same thing with a name in the file system, so unrelated processes can open it. Shell pipelines like ls | wc -l are built from pipe, fork, dup2 and exec.11 min
  2. POSIX shared memory & semaphoresShared memory lets processes map the same physical pages, so data is exchanged without copying through the kernel. It is the fastest form of IPC, but the kernel provides no synchronisation, so you add semaphores or process-shared mutexes. POSIX shared memory objects appear under /dev/shm.11 min
  3. POSIX message queuesPOSIX message queues carry discrete messages with priorities, so the reader always receives whole messages and the highest priority first. Unlike pipes, they keep message boundaries and exist independently of any process until unlinked. They suit passing small commands or jobs between processes.10 min
  4. Unix domain socketsUnix domain sockets use the full sockets API but stay on one machine, addressed by a file-system path or an abstract name. They are bidirectional, support many clients per server and can even pass open file descriptors between processes. Docker, systemd and databases all use them for local communication.12 min

07POSIX threads & synchronization

Concurrency inside one process, and how to keep it correct.

  1. Creating & joining threadsThreads are multiple flows of execution inside one process, sharing its memory, descriptors and signal handlers, each with its own stack and registers. pthread_create starts a thread running a function, and pthread_join waits for it and collects its result. Shared memory makes threads fast to communicate but easy to get wrong.12 min
  2. Race conditions & mutexesA data race happens when threads access the same memory at the same time, at least one of them writes, and nothing synchronises them. Even counter++ is a read, an add and a write, so updates get lost. A mutex makes a critical section run one thread at a time.12 min
  3. Condition variables & producer-consumerA condition variable lets a thread sleep until some shared state changes, instead of spinning. It is always paired with a mutex: lock, check the condition in a while loop, and wait, which atomically unlocks and sleeps. The bounded producer-consumer queue is the classic pattern behind thread pools.11 min
  4. Deadlocks, rwlocks & atomicsA deadlock happens when threads each hold a lock and wait for one another, so none can continue. It needs four conditions at once: mutual exclusion, hold and wait, no preemption and circular wait. A single global lock order breaks circular wait, and read-write locks or atomics reduce locking where they fit.12 min

08Memory management

Virtual memory, mapping files and what malloc actually does.

  1. Virtual memory, paging & address spaceEvery process sees its own private virtual address space, which the kernel maps to physical RAM in fixed-size pages, usually 4 KiB. The CPU's MMU translates addresses using page tables and caches recent translations in the TLB. Pages are populated lazily on first access, which is why programs can reserve far more memory than they use.13 min
  2. mmap & memory-mapped filesmmap maps a file or anonymous memory straight into your address space, so you access it with pointers instead of read and write. Shared file mappings write changes back to the file and are visible to other processes, while private mappings are copy-on-write. Large allocations, shared libraries and many databases rely on mmap.13 min
  3. malloc internals & a simple allocatormalloc is user-space library code that carves memory obtained from the kernel into small blocks. glibc grows the heap with brk for small requests and calls mmap directly for large ones, 128 KiB and up by default. Freed blocks go into bins and caches for reuse, which is why an overflow or double free corrupts state far from the bug.14 min

09Network sockets

TCP and UDP programming, from one client to thousands.

  1. Sockets API, addresses & byte orderA socket is a descriptor for a network endpoint, created with socket and then bound, connected or set to listen. Addresses are described by structs such as sockaddr_in and sockaddr_in6, and multi-byte numbers on the wire use big-endian network byte order. getaddrinfo resolves names and fills those structs for IPv4 and IPv6 alike.12 min
  2. TCP clients & serversTCP provides a reliable, ordered byte stream between two endpoints, set up with a three-way handshake. A server binds, listens and accepts connections, getting a new descriptor per client. Because TCP is a stream, your protocol must define message boundaries, for example with newlines or length prefixes.13 min
  3. UDP socketsUDP sends independent datagrams with no connection, no ordering and no delivery guarantee. Each sendto is one datagram and each recvfrom returns exactly one, so message boundaries are preserved. It suits DNS, games, streaming and metrics, where low latency matters more than perfect reliability.12 min
  4. select, poll & epollA server handling many clients cannot block on one socket while others wait. select, poll and epoll let one thread wait for readiness on many descriptors at once and then service only the ready ones. epoll is the scalable Linux choice because its cost depends on active descriptors, not on how many are watched.14 min
  5. Non-blocking I/O & event loopsAn event loop is a single thread that waits for readiness, runs a short non-blocking handler for each ready descriptor and goes back to waiting. Because handlers must never block, every connection keeps its own read buffer, write buffer and state. nginx, Redis and Node.js are built this way.13 min

10Time, timers & daemons

Measure time, schedule work and run as a background service.

  1. Clocks, sleeping & timersLinux has several clocks: CLOCK_REALTIME follows wall-clock time and can jump, while CLOCK_MONOTONIC only moves forward and is right for measuring durations. clock_gettime reads them cheaply through the vDSO. timerfd turns timers into descriptors, so periodic work fits neatly into a poll or epoll loop.13 min
  2. Classic daemonizationA daemon is a background process with no controlling terminal, such as sshd or cron. The traditional SysV recipe detaches by forking twice, starting a new session, resetting the umask and working directory and redirecting the standard streams. Under systemd most of this is unnecessary, but you will still meet it in older code.13 min
  3. Running programs as systemd servicessystemd starts, supervises and restarts services described by unit files. Modern daemons simply run in the foreground, log to stdout or stderr, and leave backgrounding, journaling, restarts and sandboxing to systemd. Type=notify lets your program tell systemd exactly when it is ready.12 min

11Capstone projects

Put every module together in two real programs.

  1. Build a mini shellA shell is the perfect capstone for processes, file descriptors and signals. Yours reads a line, splits it into commands, sets up pipes and redirections with dup2, runs each command with fork and exec, and then waits or tracks background jobs. Built-ins like cd must run inside the shell itself, because a child cannot change its parent's directory.14 min
  2. Build a concurrent TCP chat serverA chat server ties together sockets, multiplexing, buffering and protocol design. Clients connect over TCP and send newline-terminated lines, and the server broadcasts each complete line to everyone else. The hard parts are partial reads, slow clients whose buffers fill up, and disconnects in the middle of a broadcast.15 min
  3. Test, profile & ship as a serviceWorking code is not finished code. Run your capstone under sanitizers and valgrind until they report nothing, profile it with perf to see where time goes, and package it as a sandboxed systemd service. A clear README with build, run and test steps makes the project portfolio-ready.12 min