Linux – When to use /dev and /sys for userspace-kernel communication

driverslinux-kernel

I am just getting in Linux driver development and I have a conceptual question, which I think will help other newcomers into kernel development as well.

I am reading through the Linux Device Drivers book and I have completed upto Ch. 3 of the book. Until now, I have seen that by issuing open, close and other commands to files in the /dev folder, the userspace can access kernel functions.

Another method of sharing control is via files in /sys, where reading or writing from sys files can communicate with the driver.

I wanted to know what would be the use-cases for each method? Are they 2 approaches to the same task? Does one have any limitations over another? Can someone share practical examples where one might be useful over the other?

I have read the other questions here and they explain dev and sys. While that is helpful, I wanted to get a little more in-depth knowledge on how both differ and should be used.

Best Answer

Very roughly:

/dev contains device nodes, which in earlier Unix systems was the only way to interact with the kernel. There are two types of these, block devices and character devices. The corresponding API is geared to something that will allow block-based I/O (some kind of disk) or character based I/O (e.g. a serial port).

/sys (and /proc) were added later, possibly inspired by the Plan 9 OS. They provide complete directory subtrees, and the file entries in these subtrees contain text that describes the internal state of the kernel module when read, or, when written, set the internal state.

So a typical application would be:

You want to write a kernel driver for some kind of storage device? Use a /dev node to access the device itself, and /sys (or /proc) entries to fine-tune how the storage gets accessed.

Related Question