Notes

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
      1. The shell calls fork() to create a child
      1. The child opens file.txt, getting a new FD (e.g., 3)
      1. The child calls dup2(3, 1), mapping FD 1 (#stdout) to the file
      1. The child calls execve() to run ls

Shell Syntax

  • Basic Redirection:
    • command > file : Redirect stdout to file (overwrite)
    • command 2> file : Redirect stderr only
    • command &> file : Redirect both stdout and stderr
  • Combining Descriptors:
    • find / -name secret 2>/dev/null : Discard errors
    • command > file 2>&1 : Send both to the same file