Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ Based on *The Linux Programming Interface* Chapter 4 (File I/O: The Universal I/O Model) and Chapter 5 (File I/O: Further Details). See [Go io package]({{< relref "/programming/go/std/io.md" >}}) for equivalent abstractions (`io.Reader`, `io.Writer`, `io.Seeker`) in Go. ## Core Function Signatures All I/O operations on regular files, devices, pipes, sockets, and terminals use these core system calls. ### 1. open Opens an existing file or creates a new file. ```c #include int open(const char *pathname, int flags, ... /* mode_t mode */); ``` - **Return:** New file descriptor (non-negative integer) on success; `-1` on error (`errno` set) - **Parameters:** - ``: Path to the target file - ``: Bitwise OR of access mode and status flags - ``: Permissions for newly created file (`0644`, `0600`, etc.), required only when `O_CREAT` is specified #### Access Modes (Specify exactly one) - `O_RDONLY`: Open for read-only - `O_WRONLY`: Open for write-only - `O_RDWR`: Open for reading and writing #### Common Creation and Status Flags - `O_CREAT`: Create file if it does not exist - `O_EXCL`: Used with `O_CREAT`; fail atomically if file already exists (`EEXIST`). Prevents Time-of-Check to Time-of-Use (TOCTOU) race conditions when creating lock files (`app.lock`) - `O_TRUNC`: Truncate existing file length to zero - `O_APPEND`: Atomically updates file offset to end of file before each write. Prevents race conditions between multiple processes appending to the same file (eliminates `lseek(SEEK_END)` race conditions) - `O_NONBLOCK`: Open in non-blocking mode (useful for FIFOs, pipes, and sockets) - `O_CLOEXEC`: Enable close-on-exec flag atomically. Prevents file descriptor leakage across `exec` calls to child programs (stored in the process-private FD table) --- ### 2. read Reads data from an open file descriptor into a memory buffer. ```c #include ssize_t read(int fd, void *buffer, size_t count); ``` - **Return:** - `> 0`: Number of bytes actually read - `0`: End-of-File (EOF) reached - `-1`: Error occurred (`errno` set) - **Parameters:** - ``: Open file descriptor - ``: Destination memory address in RAM - ``: Maximum number of bytes to read --- ### 3. write Writes data from a memory buffer to an open file descriptor. ```c #include ssize_t write(int fd, const void *buffer, size_t count); ``` - **Return:** Number of bytes actually written on success; `-1` on error (`errno` set) - **Parameters:** - ``: Open file descriptor - ``: Source memory address in RAM - ``: Number of bytes to write --- ### 4. close Closes an open file descriptor, releasing the descriptor back to the process pool. ```c #include int close(int fd); ``` - **Return:** `0` on success; `-1` on error (`errno` set) - **Parameters:** - ``: Open file descriptor to release --- ### 5. lseek Repositions the read/write file offset of an open file descriptor. ```c #include off_t lseek(int fd, off_t offset, int whence); ``` - **Return:** Resulting file offset from beginning of file on success; `(off_t) -1` on error (`errno` set) - **Parameters:** - ``: Open file descriptor - ``: Byte displacement relative to `` - ``: Reference position for offset calculation #### Directives (`whence`) - `SEEK_SET`: Offset is set relative to the start of the file - `SEEK_CUR`: Offset is set relative to the current file position - `SEEK_END`: Offset is set relative to the end of the file (EOF) --- ## Standard File Descriptors | Descriptor | Macro | Stream | | :--- | :--- | :--- | | `0` | `STDIN_FILENO` | Standard Input (`stdin`) | | `1` | `STDOUT_FILENO` | Standard Output (`stdout`) | | `2` | `STDERR_FILENO` | Standard Error (`stderr`) | --- ## Common I/O Patterns ### 1. Sequential Read & Write Loop (System Utility Pattern) Streams data chunk by chunk from a file descriptor to standard output without requiring a null terminator. ```c #define BUF_SIZE 4096 char buffer[BUF_SIZE]; ssize_t num_read; while ((num_read = read(src_fd, buffer, BUF_SIZE)) > 0) { if (write(STDOUT_FILENO, buffer, num_read) != num_read) { perror("write failed"); break; } } if (num_read == -1) { perror("read failed"); } ``` ### 2. Read with Null-Terminated C String (String Processing Pattern) Leaves 1 byte in the buffer for the null terminator `\0` to safely process data with string functions like `printf`. ```c #define BUF_SIZE 4096 char buffer[BUF_SIZE]; ssize_t num_read; while ((num_read = read(src_fd, buffer, sizeof(buffer) - 1)) > 0) { buffer[num_read] = '\0'; printf("%s", buffer); } if (num_read == -1) { perror("read failed"); } ``` --- ## Kernel Data Structures & File Sharing (TLPI Ch 5) The Linux kernel maintains three distinct data structures to manage open files (TLPI Figure 5-2). {{< mermaid >}} graph LR subgraph "Process A" FDA1["FD 1 (stdout)"] FDA20["FD 20 (dup of 1)"] FDA2["FD 2 (stderr)"] FDA0["FD 0"] end subgraph "Process B" FDB2["FD 2 (fork from A)"] FDB3["FD 3"] end subgraph "Open File Table (System-Wide)" OFT1["Open File Description 1
• File Offset: 0
• Flags: O_WRONLY
• Ref Count: 2"] OFT2["Open File Description 2
• File Offset: 250
• Flags: O_RDWR
• Ref Count: 2"] OFT3["Open File Description 3
• File Offset: 0
• Flags: O_RDONLY
• Ref Count: 1"] OFT4["Open File Description 4
• File Offset: 100
• Flags: O_RDONLY
• Ref Count: 1"] end subgraph "i-node Table (System-Wide)" INODE1["i-node: results.log"] INODE2["i-node: terminal / pipe"] INODE3["i-node: file.txt"] end FDA1 -->|dup| OFT1 FDA20 -->|dup| OFT1 FDA2 -->|fork| OFT2 FDB2 -->|fork| OFT2 FDA0 -->|open| OFT3 FDB3 -->|open| OFT4 OFT1 --> INODE1 OFT2 --> INODE2 OFT3 --> INODE3 OFT4 --> INODE3 {{< /mermaid >}} ### File Offset Sharing Rules | Creation Method | Target Structure | Offset Sharing | | :--- | :--- | :--- | | **`dup()` / `dup2()`** | Refers to the **same Open File Description** within the same process | **Shared** (reads/writes in one FD advance the offset for both) | | **`fork()`** | Child process inherits FD table pointing to the **same Open File Description** | **Shared** (parent and child share file offsets) | | **Separate `open()` calls** | Each call allocates an **independent Open File Description** | **Independent** (each descriptor maintains its own offset even on the same i-node) | --- ## File Descriptor Duplication (`dup`, `dup2`) Duplicates an existing file descriptor by copying its pointer in the process FD table to a new entry. ```c #include int dup(int oldfd); int dup2(int oldfd, int newfd); ``` - **`dup(oldfd)`**: Allocates the lowest unused file descriptor number and copies `oldfd`'s pointer into it. - **`dup2(oldfd, newfd)`**: Atomically closes `newfd` (if already open) and copies `oldfd`'s pointer into `newfd`. Returns `newfd`. ### Standard Output Redirection Idiom (`ls > output.txt`) ```c int file_fd = open("output.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644); if (file_fd == -1) { perror("open"); } // Redirect stdout (1) to output.txt if (dup2(file_fd, STDOUT_FILENO) == -1) { perror("dup2"); } // Close original descriptor to avoid FD leaks close(file_fd); // Subsequent printf() and write(1, ...) output will go to output.txt printf("This message is written to output.txt\n"); ``` --- ## File Control (`fcntl`) Queries and modifies flags and attributes of an already open file descriptor dynamically. ```c #include int fcntl(int fd, int cmd, ... /* arg */); ``` ### Dynamic Non-Blocking Mode Idiom (`O_NONBLOCK`) ```c // 1. Fetch current file status flags int flags = fcntl(fd, F_GETFL); if (flags == -1) { perror("fcntl F_GETFL"); } // 2. Enable O_NONBLOCK bit flags |= O_NONBLOCK; // 3. Apply updated flags back to the kernel if (fcntl(fd, F_SETFL, flags) == -1) { perror("fcntl F_SETFL"); } ``` --- ## Advanced I/O ### 1. Thread-Safe Positional I/O (`pread`, `pwrite`) Performs I/O at a specified offset without altering the current file offset in the Open File Description. ```c #include ssize_t pread(int fd, void *buf, size_t count, off_t offset); ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); ``` - Atomically combines seek and read/write operations into a single system call. - Safe for concurrent multi-threaded access on a shared file descriptor without mutex synchronization. ### 2. Scatter-Gather I/O (`readv`, `writev`) Transfers data between a single file descriptor and multiple non-contiguous memory buffers in a single system call. ```c #include struct iovec { void *iov_base; // Starting address of buffer size_t iov_len; // Length of buffer in bytes }; ssize_t readv(int fd, const struct iovec *iov, int iovcnt); ssize_t writev(int fd, const struct iovec *iov, int iovcnt); ``` #### Atomic Multi-Buffer Write Pattern (Header + Payload) ```c char header[] = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"; char body[] = "HELLO"; struct iovec iov[2]; iov[0].iov_base = header; iov[0].iov_len = sizeof(header) - 1; iov[1].iov_base = body; iov[1].iov_len = sizeof(body) - 1; // Atomic transmission without memcpy buffer concatenation ssize_t total_written = writev(sock_fd, iov, 2); if (total_written == -1) { perror("writev"); } ```