A file descriptor (FD) is a non-negative integer that uniquely identifies an open file, socket, or other I/O resource in a Linux or Unix-like system. Every process has a table of file descriptors that track open files.
1. Standard File Descriptors
Every process starts with three standard file descriptors:
FD Number
Name
Description
0
stdin
Standard input (keyboard, pipe input)
1
stdout
Standard output (console, file, pipe output)
2
stderr
Standard error output (for error messages)
For example:
echo "Hello" > output.txt # Redirects stdout (FD 1) to a fileecho "Error!" 2> error.txt # Redirects stderr (FD 2) to a file
2. Viewing Open File Descriptors
Each process has an open file descriptor table stored in /proc/<PID>/fd/.
Occurs when a process exceeds the ulimit -n value. Fix:
Increase file descriptor limits as explained above.
Check for file descriptor leaks:
lsof -p <PID>
Close unused file descriptors in scripts:
exec 3>&- # Close FD 3
6. Practical Example: Managing File Descriptors in a Script
#!/bin/bashexec 3>logfile.txt # Open FD 3 for writingecho "Logging info..." >&3 # Write to FD 3exec 3>&- # Close FD 3
7. File Descriptors in Networking
Sockets and pipes also use file descriptors. To monitor active network connections:
lsof -i -n -P
To check open network ports:
netstat -tulnp
Key Takeaways
✅ Every open file/socket is assigned a file descriptor.
✅ ulimit -n controls max open FDs per process.
✅ Use lsof, /proc/<PID>/fd/, and ulimit to monitor & manage FDs.
✅ Increase FD limits if needed to prevent errors in high-traffic applications.
Would you like a deep dive into debugging FD leaks or programming with FDs in C/Python? 🚀