File Descriptors
In the kernel, every #process is represented by a struct task_struct. Inside this struct is a pointer to struct files_struct, which contains the File Descriptor Table.
- FD Index: A non-negative integer used by system calls (
read,write,close) [3.2]. - Standard FDs:
0: #stdin (keyboard)1: #stdout (terminal)2: #stderr (error logs)
Redirection Mechanics
Redirection is achieved via the #dup2() system call, which clones a file descriptor into another index.
- Example:
ls > file.txt-
- The shell calls
fork()to create a child
- The shell calls
-
- The child opens
file.txt, getting a new FD (e.g., 3)
- The child opens
-
- The child calls
dup2(3, 1), mapping FD 1 (#stdout) to the file
- The child calls
-
- The child calls
execve()to runls
- The child calls
-
Shell Syntax
- Basic Redirection:
command > file: Redirect stdout to file (overwrite)command 2> file: Redirect stderr onlycommand &> file: Redirect both stdout and stderr
- Combining Descriptors:
find / -name secret 2>/dev/null: Discard errorscommand > file 2>&1: Send both to the same file