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).