Pseudoterminals (PTY), File-Descriptor Redirection & sudo PATH Isolation
Misordering 2>&1 by two tokens silently drops compiler errors from build logs, piping make | tee masks broken builds with exit code zero, and running sudo make erases your cross-compiler from PATH via /etc/sudoers security policy.
What you'll learn
- Contrast kernel n_tty signal/canonical processing on /dev/pts/N against raw 8N1 serial byte streams on /dev/ttyUSB0.
- Trace exact file-descriptor table mutations across dup2(1, 2) redirection orders and pipefail shell pipelines.
- Prevent sudo secure_path cross-compiler loss by separating unprivileged compilation from staged root installation.
Where Bytes and Signals Actually Go Inside a Terminal Window
When you open an SSH session or a desktop terminal tab (Ctrl-Shift-T) and run ps -ef, the TTY column reports pts/0 rather than a hardware UART. Every terminal tab allocates a pseudoterminal (PTY) pair inside the Linux kernel: the terminal emulator holds the master file descriptor from /dev/ptmx, the shell attaches stdin (0), stdout (1), and stderr (2) to /dev/pts/0, and the n_tty line discipline sits in between.
Pressing Ctrl-C sends byte 0x03; n_tty intercepts it under ISIG mode and delivers SIGINT to the local foreground process group. By contrast, a serial program (picocom or minicom) puts its local /dev/ttyUSB0 descriptor into cfmakeraw() mode so 0x03 travels across the physical wire to interrupt U-Boot or a target process!
Two daily build failures stem directly from how shells wire descriptors and environments around child processes. Writing make 2>&1 >build.log leaves every gcc error on screen and absent from build.log, while make | tee build.log reports exit status 0 in CI even when compilation aborts! Worse, typing sudo make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- suddenly fails with arm-linux-gnueabihf-gcc: Command not found even though which found the compiler one second earlier.
Figure 1.2a. Redirection operators mutate the child file-descriptor table sequentially from left to right; 2>&1 copies the current target of fd 1, not its future target.
mental model: Picture fd 1 (stdout) and fd 2 (stderr) as two clipboards holding room numbers—both initially say Room pts/0. Writing 2>&1 does not glue the two clipboards together forever; it tells the clerk: copy whatever room number is written on Clipboard 1 right now onto Clipboard 2. If you copy Clipboard 1 onto Clipboard 2 first (2>&1, both say pts/0) and then erase Clipboard 1 to write build.log (>build.log), Clipboard 2 still says pts/0!
Where it stops working: The clipboard metaphor shows pointer assignment order, whereas in the Linux kernel dup2(1, 2) increments the reference count on a shared struct file description—meaning fd 1 and fd 2 also share a single atomic f_pos file offset rather than overwriting each other at byte 0.
definition (Open File Description Sharing (dup2) and sudo secure_path): POSIX separates a process-private file descriptor integer (0, 1, 2) from the kernel-wide open file description (struct file holding f_pos and O_APPEND flags). Calling dup2(1, 2) closes fd 2 and points slot 2 at the exact struct file currently referenced by slot 1. Separately, sudo enforces privilege-escalation hygiene via Defaults env_reset and Defaults secure_path in /etc/sudoers, discarding caller PATH and LD_LIBRARY_PATH variables so an unprivileged user cannot trick a root command into executing a trojan ls or gcc placed in /tmp.
- Step 1. Enable set -euo pipefail at the top of build and deployment scripts so downstream loggers like tee cannot mask compiler failures.
- Step 2. Redirect fd 1 to the target file before evaluating 2>&1 so stderr inherits the newly opened log description.
- Step 3. Run all kernel, U-Boot, and rootfs compilation steps as an unprivileged user so cross-compilers remain in PATH and object files stay user-owned.
- Step 4. Stage kernel modules into an unprivileged INSTALL_MOD_PATH directory instead of running sudo make against the host /lib/modules tree.
Figure 1.2b. Order >log before 2>&1, set pipefail on build pipes, and never compile under sudo.
Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
Inside fs/file.c, each task holds current->files->fdt->fd[], an array mapping small integers (0, 1, 2) to struct file * pointers. Notice why cmd >build.log 2>build.log (opening the same file twice independently) is a classic bug: two separate open() calls allocate two independent struct file objects, each starting at f_pos = 0, so stdout and stderr overwrite one another's bytes! Using >build.log 2>&1 calls open() once and dup2(1, 2) once, sharing a single f_pos cursor.
When chaining processes with | (make -j8 2>&1 | tee build.log), the shell creates an anonymous pipe2() buffer, binds the left child's fd 1 and fd 2 to the pipe write end, and binds tee's fd 0 to the read end. By POSIX default, $? equals only the rightmost command's exit status (tee returns 0!), whereas set -o pipefail surfaces the rightmost non-zero exit code across the entire pipeline.
Finally, /etc/sudoers compiles Defaults secure_path="/usr/local/sbin:...:/bin". Even sudo -E refuses to preserve PATH when secure_path is active, explaining why cross-compilation always belongs in unprivileged user space.
Figure 1.2b. Sharing one struct file via dup2(1, 2) serializes f_pos offsets, while pipefail preserves left-hand compiler failures.
| Shell Construct | fd 1 Target | fd 2 Target | Failure / Production Consequence | |
|---|---|---|---|---|
make >build.log 2>&1 | build.log (struct file A) | build.log (struct file A) | Unified chronological log; single shared f_pos offset | |
make 2>&1 >build.log | build.log (struct file A) | /dev/pts/N (terminal) | Errors vanish from build.log; CI log lacks compiler diagnostics | |
make >build.log 2>build.log | build.log (struct file A) | build.log (struct file B) | Two independent f_pos = 0 cursors overwrite each other! | |
| `make 2>&1 | tee build.log (no pipefail`) | Pipe -> tee (pts/N + log) | Pipe -> tee (pts/N + log) | Log is complete, but $? is 0 (tee) even when make fails! |
learner@ksa:~/gl-e00/m01-l02$ bat -H 2 -H 12 safe_cross_build.sh File: safe_cross_build.sh #!/usr/bin/env bash set -euo pipefail export PATH="/opt/toolchains/arm-gnu-toolchain/bin:${PATH}" STAGE_DIR="${PWD}/_rootfs_stage" LOG_FILE="${PWD}/build_kernel.log" # 1. Unprivileged cross-build: stdout + stderr share pipe into tee; pipefail guards rc make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- -j"$(nproc)" zImage modules dtbs 2>&1 | tee "${LOG_FILE}" # 2. Stage modules without sudo (preserves CROSS_COMPILE in PATH and user file ownership) make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- INSTALL_MOD_PATH="${STAGE_DIR}" modules_install >"${STAGE_DIR}.log" 2>&1- set -euo pipefail ensures a non-zero exit from make propagates past tee instead of reporting success.
- INSTALL_MOD_PATH stages /lib/modules unprivileged, avoiding sudo secure_path stripping of arm-linux-gnueabihf-.
dup2(2) GL-E00 Quick Reference dup2(2) NAME dup2, pts, sudoers - duplicate file descriptors, PTY pairs, and sudo PATH policy SYNOPSIS #include <unistd.h> int dup2(int oldfd, int newfd); DESCRIPTION dup2() makes newfd refer to the same open file description (struct file) as oldfd. In POSIX sh: >file 2>&1 opens file on fd 1, then calls dup2(1, 2). 2>&1 >file calls dup2(1, 2) while fd 1 is still /dev/pts/N, then reopens fd 1. NOTES ON SUDOERS /etc/sudoers 'Defaults secure_path' overrides PATH even under 'sudo -E'. Never run 'sudo make' on Linux kernel or U-Boot trees; stage via INSTALL_MOD_PATH. Kernel Systems Academy Lesson 1.2 dup2(2) GL-E00 quick reference · full manual page: man 2 dup2 Proving dup2() Redirection Order With Real Kernel Pipes in C11
Rather than memorizing shell folklore, we can execute the exact kernel pipe() and dup2() sequences in ISO C11 and measure how many bytes arrive at the terminal stream versus the log stream. In verify.c, run_redirection_case() allocates two real kernel pipes—one standing in for /dev/pts/0 and one standing in for build.log—saves original stdout/stderr via dup(), applies dup2() in both >log 2>&1 and 2>&1 >log orders, and writes OUT\n to fd 1 plus ERR\n to fd 2.
We also test sudo secure_path scrubbing by verifying whether /opt/toolchains/arm/bin survives a reset to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Running under strace -e trace=pipe2,dup2,write,read,close exposes every single kernel descriptor re-binding step directly in the captured trace.
learner@ksa:~/gl-e00/m01-l02$ bat -H 25 -H 29 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdio.h> #include <string.h> #include <unistd.h> static int drain_pipe(int rfd, char *buf, size_t cap) { ssize_t n = read(rfd, buf, cap - 1); if (n < 0) n = 0; buf[n] = '\0'; return (int)n; } static int run_redirection_case(int log_before_dup, char *pts_out, char *log_out) { int pts_p[2], log_p[2]; if (pipe(pts_p) != 0 || pipe(log_p) != 0) return -1; int saved_out = dup(STDOUT_FILENO); int saved_err = dup(STDERR_FILENO); /* Initial terminal state: both fd 1 and fd 2 point to pts_p[1] */ dup2(pts_p[1], STDOUT_FILENO); dup2(pts_p[1], STDERR_FILENO); if (log_before_dup) { /* Equivalent to: cmd >build.log 2>&1 */ dup2(log_p[1], STDOUT_FILENO); dup2(STDOUT_FILENO, STDERR_FILENO); } else { /* Equivalent to: cmd 2>&1 >build.log */ dup2(STDOUT_FILENO, STDERR_FILENO); dup2(log_p[1], STDOUT_FILENO); } const char *m_out = "OUT\n"; const char *m_err = "ERR\n"; if (write(STDOUT_FILENO, m_out, 4) != 4) return -2; if (write(STDERR_FILENO, m_err, 4) != 4) return -3; /* Restore real stdout/stderr and close write ends before draining */ dup2(saved_out, STDOUT_FILENO); dup2(saved_err, STDERR_FILENO); close(saved_out); close(saved_err); close(pts_p[1]); close(log_p[1]); drain_pipe(pts_p[0], pts_out, 32); drain_pipe(log_p[0], log_out, 32); close(pts_p[0]); close(log_p[0]); return 0; } static int path_contains_dir(const char *path_env, const char *needle) { size_t nlen = strlen(needle); const char *p = path_env; while (*p) { const char *sep = strchr(p, ':'); size_t slen = sep ? (size_t)(sep - p) : strlen(p); if (slen == nlen && memcmp(p, needle, nlen) == 0) return 1; if (!sep) break; p = sep + 1; } return 0; } int main(void) { char pts_ok[32] = {0}, log_ok[32] = {0}; char pts_bad[32] = {0}, log_bad[32] = {0}; if (run_redirection_case(1, pts_ok, log_ok) != 0) return 1; if (run_redirection_case(0, pts_bad, log_bad) != 0) return 1; const char *user_path = "/opt/toolchains/arm/bin:/usr/bin:/bin"; const char *sudo_secure_path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; int in_user = path_contains_dir(user_path, "/opt/toolchains/arm/bin"); int in_sudo = path_contains_dir(sudo_secure_path, "/opt/toolchains/arm/bin"); printf("case_gt_log_2gt1: pts_bytes=%zu log=[%.3s+%.3s] (%zuB)\n", strlen(pts_ok), log_ok, log_ok + 4, strlen(log_ok)); printf("case_2gt1_gt_log: pts=[%.3s] (%zuB) log=[%.3s] (%zuB)\n", pts_bad, strlen(pts_bad), log_bad, strlen(log_bad)); printf("cross_cc_visible: user_shell=%d sudo_secure_path=%d\n", in_user, in_sudo); return (strlen(pts_ok) == 0 && strcmp(log_ok, "OUT\nERR\n") == 0 && strcmp(pts_bad, "ERR\n") == 0 && strcmp(log_bad, "OUT\n") == 0 && in_user == 1 && in_sudo == 0) ? 0 : 1; }- cmd >log 2>&1 binds fd 1 to log_p[1] first, so dup2(1, 2) routes both OUT and ERR (8 bytes) into log_p.
- cmd 2>&1 >log duplicates fd 1 while it still points to pts_p[1], leaking ERR (4 bytes) to the terminal.
Inspecting Real pipe2() and dup2() Syscalls Under strace
Examine the captured shell output and strace trace below. In case_gt_log_2gt1, 0 bytes leak to pts and all 8 bytes (OUT+ERR) arrive sequentially in log. In case_2gt1_gt_log, ERR (4B) leaks onto pts while log receives only OUT (4B). Reading the strace window confirms the kernel sequence directly: pipe2() allocates descriptor pairs, dup2() rewrites fd 1 and fd 2 in exact call order, and read() drains each buffer deterministically.
learner@ksa:~/gl-e00/m01-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l02./verifycase_gt_log_2gt1: pts_bytes=0 log=[OUT+ERR] (8B)case_2gt1_gt_log: pts=[ERR] (4B) log=[OUT] (4B)cross_cc_visible: user_shell=1 sudo_secure_path=0learner@ksa:~/gl-e00/m01-l02learner@ksa:~/gl-e00/m01-l02strace -e trace=pipe2,dup2,write,read,close \./verifyclose(3) = 0read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832close(3) = 0pipe2([3, 4], 0) = 0pipe2([5, 6], 0) = 0dup2(4, 1) = 1dup2(4, 2) = 2dup2(6, 1) = 1dup2(1, 2) = 2write(1, "OUT\n", 4) = 4write(2, "ERR\n", 4) = 4dup2(7, 1) = 1dup2(8, 2) = 2close(7) = 0close(8) = 0close(4) = 0close(6) = 0read(3, "", 31) = 0read(5, "OUT\nERR\n", 31) = 8close(3) = 0close(5) = 0pipe2([3, 4], 0) = 0pipe2([5, 6], 0) = 0dup2(4, 1) = 1dup2(4, 2) = 2dup2(1, 2) = 2dup2(6, 1) = 1write(1, "OUT\n", 4) = 4write(2, "ERR\n", 4) = 4dup2(7, 1) = 1dup2(8, 2) = 2close(7) = 0close(8) = 0close(4) = 0close(6) = 0read(3, "ERR\n", 31) = 4read(5, "OUT\n", 31) = 4close(3) = 0close(5) = 0write(1, "case_gt_log_2gt1: pts_bytes=0 lo"..., 147) = 147+++ exited with 0 +++Subtle Redirection, PTY Signal & sudo Build Traps
Understanding descriptor tables and line disciplines eliminates mysterious terminal behavior across both host builds and target UART consoles. Always pair 2>&1 | tee with set -euo pipefail, keep U-Boot and Linux kernel builds completely out of sudo, and distinguish local PTY SIGINT handling from raw UART wire bytes.
Pressing Ctrl-C Kills the Host Serial Program Instead of Target ping:
- Symptom: While logged into a target board over a naive script (
cat /dev/ttyUSB0), pressingCtrl-Ckills the localcatcommand on the host instead of stoppingpingon the board. - Root Cause: The host shell's
/dev/pts/Nn_ttyline discipline still hasISIGenabled, so0x03generatesSIGINTlocally on the host before ever reaching/dev/ttyUSB0. - Fix: Use a dedicated serial terminal (
picocom -b 115200 /dev/ttyBENCH0orminicom) that puts the local PTY intocfmakeraw()(~ISIG & ~ICANON & ~ECHO), forwarding0x03verbatim over UART and reserving an escape chord (Ctrl-A Ctrl-X) for host exit.
Root-Owned Build Artifacts After One Accidental sudo make:
- Symptom: Subsequent normal
makeinvocations fail withFatal error: can't create scripts/basic/.fixdep.d: Permission denied. - Root Cause: A single
sudo makeleft.o,.cmd, andinclude/config/directories owned byUID 0:0inside your working tree, blocking unprivileged compiler updates. - Fix: Reclaim ownership once via
sudo chown -R "$(id -u):$(id -g)" ., and never invokesudoformenuconfig,zImage,dtbs, ormodulesbuilds.
Guided Practice
Modify verify.c to add a third helper run_dual_open_case() that opens a temporary file twice (fd_a = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600) and fd_b = open(path, O_WRONLY)) without O_APPEND, binds fd 1 to fd_a and fd 2 to fd_b, and writes "STDOUT_LINE\n" followed by "ERR\n". Inspect the resulting file bytes to see "ERR\nUT_LINE\n" clobbering at byte offset 0!
Independent Practice
Write a POSIX C11 wrapper using fork(), pipe(), dup2(), and waitpid() that runs two child stages (stage1 exiting with code 2 and stage2 exiting with code 0) and implements pipefail semantics in C by returning the rightmost non-zero WEXITSTATUS.
Verification Checks
Key takeaways
- A pseudoterminal pairs a /dev/ptmx master descriptor owned by the terminal emulator with a /dev/pts/N replica governed by the Linux kernel n_tty line discipline.
- Shell redirections execute strictly left to right via dup2(oldfd, newfd): >build.log 2>&1 sends both streams to build.log, whereas 2>&1 >build.log leaves stderr pointing at the terminal.
- Enabling set -euo pipefail causes a pipeline such as make 2>&1 | tee build.log to return the non-zero exit code of the failing build stage instead of tee's zero exit status.
- Default /etc/sudoers env_reset and secure_path policies replace user PATH variables during sudo execution, hiding user-installed ARM cross-toolchains unless builds run unprivileged with DESTDIR or INSTALL_MOD_PATH.