The Hidden Power of Unix File Descriptors

Tom Deneire
CodeX
Published in
5 min readSep 10, 2022

--

Photo by Erol Ahmed on Unsplash

File descriptors

In Unix and Unix-like operating systems, a file descriptor is a unique identifier for a file. For instance, /etc/environment is the descriptor that refers to the system-wide configuration file for environment variables. Nothing special, so far.

Regular files, symbolic links, directories

But that’s not all there is to the story. You probably know that besides regular files, file descriptors can also refer to other file types, such as symbolic links and directories.

Symbolic links are links to files that behave just like the file itself, but you can move them around, make copies of them and remove them, without affecting the original file. And if you modify the contents of either the original or a symbolic link, both are kept in sync. This is very handy, for instance, if you want to share files across different users or for file management. On my machine, for instance, I like to keep my work projects close at hand withhome/tdeneire/work, but this is actually just a symbolic link to /home/tdeneire/backup/Dropbox/projects/work (which is much less manageable) so that the whole directory is automatically backed up to the cloud…

This example of a symbolic link to a directory shows how, in Unix, directories are a file type as well. Many of the operations that are valid on regular files (removing, copying, moving, renaming, …) are valid on directories too. Again, this is done using the file descriptor, e.g. the home directory, in my case /home/tdeneire .

Device files

The POSIX standard defines more file types still, which can be addressed with file descriptors. For instance, so-called Unix domain sockets, which are a data communications endpoint for exchanging data in the kernel between processes. Another interesting category are device files, traditionally mounted in /dev, which are interfaces to a device driver that appear in the file system as if they were ordinary files. Perhaps the most interesting of these, in this context, are the so-called pseudo-device files. These do not correspond to physical hardware devices, but provide certain tools for the operating system. One example is /dev/null , which accepts and discards all input written to…

--

--