What are files? Files are names in a directory structure which denote objects. When you open a file like /home/joe/foo.txt
, the operating system creates an object in memory representing that file (or finds an existing one, if the file is already open), binds a descriptor to it which is returned and then operations on that file descriptor (like read
and write
) are directed, through the object, into file system code which manipulates the file's representation on disk.
Device entries are also names in the directory structure. When you open some /dev/foo
, the operating system creates an in-memory object representing the device, or finds an existing one (in which case there may be an error if the device does not support multiple opens!). If successful, it binds a new file descriptor to the device obejct and returns that descriptor to your program. The object is configured in such a way that the operations like read
and write
on the descriptor are directed to call into the specific device driver for device foo
, and correspond to doing some kind of I/O with that device.
Such entries in /dev/
are not files; a better name for them is "device nodes" (a justification for which is the name of the mknod
command). Only when programmers and sysadmins are speaking very loosely do they call them "device files".
When you do cat > /dev/tty
, there isn't anything which is "erasing" data "on the other end". Well, not exactly. Basically, cat
is calling write
on a descriptor, and this results in a chain of function calls which ends up somewhere in the kernel's tty subsystem. The data is handed off to a tty driver which will send the data into a serial port, or socket, or into a console device which paints characters on the screen or whatever. Virtual terminals like xterm
use a pair of devices: a master and slave pseudo-tty. If a tty is connected to a pseudo-tty device, then cat > /dev/tty
writes go through a kind of "trombone": they bubble up on the master side of the pseudo-tty, where in fact there is a while (1)
loop in some user-space C program receiving the bytes, like from a pipe. That program is xterm
(or whatever); it removes the data and draws the characters in its window, scrolls the window, etc.