Linux – Where does a device file come from

devicesdriverslinuxlinux-kernel

I'm reading through the Linux Kernel Module programming guide and I am a bit onfused about how device drivers work.

I tried following along and making a basic device driver, which shows up in /proc/devices, which is great. According to the guide, to interface with the driver in Linux, a userspace program can interact with that device's device file in /dev/. Right now though, the module I've written doesn't generate a device file. What manages the generation of new files? Is that something I'm supposed to do in module_init?

And assuming I've gone and gotten a device file made, is interacting with the driver, in say a C++ program, just opening up an fstream and reading or writing that file, or are there specific libraries used to interact with device files in userspace?

Best Answer

Files in /dev are mostly created by the udev process which receives events from the kernel by listening to the netlink socket for NETLINK_KOBJECT_UEVENT (see man 7 netlink). The events are sent when a new kernel object (kobject) is created. These objects are also seen in the /sys sysfs filesystem. In particular, files named dev in the /sys/devices subtree hold the major and minor number of the node to use for a given device. Eg

$ cat /sys/devices/pnp0/00:05/tty/ttyS0/dev
4:64

This is explained in this online chapter 14 pdf of Linux Device Drivers, Third Edition from 2005, The Linux Device Model. It is a little outdated and does not mention netlink for example.

Related Question