Part 3 of 7 · 2 min read
Block and character devices
Think of a library and a tap. In the library you ask for book number 5,000 and get exactly that book, at any time and in any order. From a tap you get a stream, and you cannot ask for the water of three minutes ago. The analogy stops in one place: a tap cannot go back, while some character devices, like a tape or a terminal, differ in their own ways.
In plain words: Unix shows every device as a file in /dev. A block device stores fixed-size blocks, and each block can be read or written by number in any order. Disks are block devices. A character device delivers or accepts a stream of bytes and has no block numbers. Terminals, keyboards and serial ports are character devices. A device file has a major number, which says which driver handles it, and a minor number, which says which unit of that driver. The ls -l listing shows b for a block device and c for a character device.
A worked example. On the test machine:
$ ls -l /dev/vda /dev/null /dev/tty /dev/zero
brw------- 1 root root 254, 0 Nov 19 00:15 /dev/vda
crw-rw-rw- 1 root root 1, 3 Nov 19 00:15 /dev/null
crw-rw-rw- 1 root root 5, 0 Nov 19 00:15 /dev/tty
crw-rw-rw- 1 root root 1, 5 Nov 19 00:15 /dev/zero
/dev/vda has major 254, which is the virtblk driver in the list of block devices in /proc/devices. /dev/null and /dev/zero both have major 1 and the minors 3 and 5. They are two units of the same driver, the memory character devices. /dev/null discards everything written to it. /dev/zero returns endless zero bytes when read.
The key lines. The first letter of the mode string gives the kind. A program can ask for it with stat and test S_ISBLK or S_ISCHR.
Block device and character device
A block device is a device that stores data in fixed-size blocks that can be addressed and accessed in any order. A character device is a device that is accessed as a stream of bytes with no addressing. Both appear as special files in /dev, identified by a major number (the driver) and a minor number (the unit).
Example: /dev/vda is a block device, and /dev/tty is a character device.
Check yourself:
1. What does the first letter b or c in ls -l mean?
2. What do the major and the minor number identify?
3. Why is a keyboard a character device and a disk a block device?