Character device

On this page 7

A character device is a device that the kernel exposes as an unstructured stream of bytes, read and written sequentially without a fixed block size or a buffer cache in between. In operating systems, and specifically in the area of Drivers & devices, it is one of the two classic device classes of Unix-like kernels, alongside the block device, and it covers hardware such as terminals, serial ports, mice, sound interfaces, random number generators and many vendor-specific controllers.

Applications reach a character device through a device file, usually under /dev, and use ordinary system calls such as open, read, write and ioctl. The kernel routes each call directly to the driver’s entry points, so the driver alone decides what a read or a write means for its hardware.

How a character device handles I/O requests

A character device handles I/O by passing each system call straight to its driver, without the page cache or an I/O scheduler in the path. On Linux, the driver registers a struct file_operations table with function pointers for open, release, read, write, poll, mmap and unlocked_ioctl, and the virtual file system calls those functions when a process acts on the device file.

Each device is identified by a major and minor number pair. The major number traditionally selects the driver, while the minor number tells the driver which instance or channel is meant, for example which serial port. Modern Linux allocates these numbers dynamically with alloc_chrdev_region and creates the nodes in /dev through udev or devtmpfs.

Because there is no generic buffering, the driver controls blocking behavior. A read on a keyboard or a serial line normally sleeps until data arrives, typically woken by an interrupt service routine, while a file opened with O_NONBLOCK returns immediately with EAGAIN. The table below lists the main entry points and what they usually do.

Entry pointTriggered byTypical job
openopen() on the device fileCheck access, allocate per-file state
readread()Copy data from the device or a ring buffer to user space
writewrite()Copy user data to the device or a transmit queue
pollpoll(), select(), epollReport readiness without blocking
ioctlioctl()Device-specific control commands
mmapmmap()Map device memory or a shared buffer into the process
releaseLast close()Free state, stop hardware activity
Typical entry points of a character device driver

Character devices compared with block and network devices

The essential difference is that a block device offers random access to fixed-size blocks through the buffer cache, while a character device offers sequential, driver-defined access. Network interfaces form a third class in Linux: they have no device file at all and are reached through sockets.

PropertyCharacter deviceBlock deviceNetwork device
Unit of transferArbitrary byte countFixed blocks, often 512 B or 4 KiBPackets
Random accessUsually notYes, by block offsetNo
Kernel cachingNone by defaultPage cacheSocket buffers
I/O schedulerNot usedUsed for request orderingQueueing disciplines
Access pathDevice file in /devDevice file in /devSocket API, no device file
Typical examplesTerminals, serial ports, sensorsDisks, SSDs, partitionsEthernet, Wi-Fi interfaces
Device classes in Unix-like kernels

The boundary is a matter of interface, not hardware. A raw disk can be reached through a character interface on some systems, and FreeBSD removed block device nodes entirely in favor of character access to storage. Windows does not use the Unix classification; its drivers expose device objects reached through CreateFile and DeviceIoControl, which play a comparable role.

Common character devices and their roles

Most systems contain dozens of character devices, many of which are virtual devices with no physical hardware behind them. Pseudo-devices such as /dev/null and /dev/urandom are implemented entirely in the kernel yet follow exactly the same interface rules.

Device fileBackingPurpose
/dev/nullPseudo-deviceDiscards writes, returns end of file on read
/dev/zeroPseudo-deviceReturns an endless stream of zero bytes
/dev/urandomKernel entropy poolCryptographically secure random bytes
/dev/ttyS0UART hardwareFirst serial port
/dev/input/event0Input subsystemKeyboard, mouse or touch events
/dev/i2c-1I2C bus adapterUser-space access to I2C peripherals
/dev/nvidia0GPU driverControl channel for graphics workloads
Representative character devices on Linux

Subsystems such as the misc device framework let small drivers register a single character device with a shared major number, which avoids exhausting the major number space for simple interfaces like watchdog timers.

Designing and using a character device interface

A well-designed character device keeps the data path in read and write and moves configuration into a small, versioned set of ioctl commands or sysfs attributes. Overloading ioctl with dozens of loosely defined commands is a frequent source of compatibility and security problems, because every command parses untrusted data from user space.

Performance depends heavily on how data crosses the kernel boundary. Copying through copy_to_user is safe and simple, but for high-rate devices such as cameras or data acquisition cards a driver often implements mmap of a shared ring buffer, sometimes combined with direct memory access, so that the process reads data without a copy per sample.

SituationRecommended methodReason
Low data rate, simple protocolread and write with copyingMinimal code, easy to secure
Event-driven inputBlocking read plus pollProcess sleeps until the interrupt signals data
High-throughput streamingmmap of a DMA ring bufferAvoids per-byte copies and system calls
Occasional configurationioctl or sysfs attributeKeeps control separate from the data path
Choosing a transfer method for a character device

Limitations and common mistakes

Character devices give drivers great freedom, and that freedom produces typical failure modes. Since the kernel imposes little structure, correctness depends on the driver author handling concurrency, partial transfers and user pointers properly.

  • Ignoring short reads and writes: applications must loop, because a read may legally return fewer bytes than requested.
  • Missing locking: several processes can open the same device, so shared state needs a mutex or spinlock.
  • Unchecked user pointers: dereferencing a user address directly instead of using copy helpers leads to crashes or privilege escalation.
  • Permissive device file modes: a world-writable node can let any user reprogram hardware.
  • Assuming seek works: most character devices return an error or ignore the offset on lseek.

Explained without jargon

A character device is like a water tap for data. You open it and data flows out, or you pour data in, one piece after another. You cannot jump to the middle of the stream, and nothing is stored in a tank along the way.

A disk is different: it is more like a filing cabinet with numbered drawers, where you can open any drawer you like. Keyboards, serial cables and random number sources behave like taps, so the operating system treats them as streams instead of storage.

A typical use case

An engineer at a small manufacturing plant connects a barcode scanner over a USB serial adapter to a Linux workstation. The kernel’s USB serial driver creates the character device /dev/ttyUSB0, and a udev rule gives the scanner a stable name and grants access to a dedicated service account instead of root.

The inventory application opens the device file, sets 9600 baud and raw mode through the terminal ioctl interface, and then blocks in read until a scan arrives. Each scan wakes the process within milliseconds, and the program parses the bytes up to the line terminator. Because the code handles short reads and reconnects after the adapter is unplugged, the station runs for months with no lost scans and no polling overhead.