How does file descriptor management work in Linux (0/1/2, /dev/null, redirection internals)?
Answer
Every process inherits three open file descriptors (FDs) by convention: FD 0 (stdin), FD 1 (stdout), FD 2 (stderr). All I/O in Linux is file I/O — network sockets, pipes, and devices are all FDs. Redirection works by duplicating and replacing FDs: 2>&1 duplicates FD 1 into FD 2 (stderr now goes where stdout goes). > file opens the file and assigns FD 1 to it. /dev/null is a character device that discards all writes and returns EOF on reads — command > /dev/null 2>&1 silences both streams. Order matters: 2>&1 > file is wrong (redirects stderr to the current stdout, then redirects stdout to file, leaving stderr pointing to original stdout). FD limits per process are set by ulimit -n (view with ulimit -n, typically 1024 or 65536 on production servers — insufficient limits are a common cause of "too many open files" errors).
Previous
Describe the Linux boot process from BIOS to init.
Next
What are the key differences between POSIX sh and bash?
More Linux / Shell Scripting Questions
View all →- Advanced What are Linux namespaces and cgroups, and how do they underpin containers?
- Advanced How do iptables and nftables handle packet filtering rules?
- Advanced What is LVM (Logical Volume Manager) and what problems does it solve?
- Advanced How does /etc/fstab work and what are important mount options?
- Advanced How do sysctl kernel parameters work and what are important tuning examples?