Character Device Files – How Do Character Device or Character Special Files Work?

driversfiles

I am trying to understand character special files. From wikipedia, I understand that these files
"provide an interface" for devices that transmit data one character at a time. My understanding is that the system somehow calls the character device instead of calling the device driver directly. But how does the file provide this interface? Is it an executable that translates the system call? Can someone explain what's up.

Best Answer

They are actually just that - interfaces. Encoded by a "major" and "minor" number they provide a hook to the kernel.

They come in two flavors (well, three, but named pipes are out of the scope of this explanation for now): Character Devices and Block Devices.

Block Devices tend to be storage devices, capable of buffering output and storing data for later retrieval.

Character Devices are things like audio or graphics cards, or input devices like keyboard and mouse.

In each case, when the kernel loads the correct driver (either at boot time, or via programs like udev) it scans the various buses to see if any devices handled by that driver are actually present on the system. If so, it sets up a device that 'listens' on the appropriate major/minor number.

(For instance, the Digital Signal Processor of the first audio card found by your system gets the major/minor number pair of 14/3; the second gets 14,35, etc.)

It's up to udev to create an entry in /dev named dsp as a character device marked major 14 minor 3.

(In significantly older or minimum-footprint versions of Linux, /dev/ may not be dynamically loaded but just contain all possible device files statically.)

Then, when a userspace program tries to access a file that's marked as a 'character special file' with the appropriate major/minor number (for instance, your audio player trying to send digital audio to /dev/dsp ), the kernel knows that this data needs to be transmitted via the driver that major/minor number is attached to; presumably said driver knows what to do with it in turn.

Related Question