Linux内核模块中class、class device等概念及相关函数作用问询
Great question—this is such a common sticking point when you're first diving into Linux kernel module development, especially since the API has shifted over time. Let's break down these core concepts and clarify which functions handle device node creation.
Core Definitions
Let’s start with the key terms you’re asking about:
- Class: A high-level abstraction that groups devices with similar functionality. Think of it as a category—like
inputfor keyboards/mice,ttyfor terminals, or a custom class you make for your character device. It lives in/sys/class/and helps userspace tools (like udev) recognize what kind of device they’re dealing with. - Device: A concrete instance of a physical or logical hardware entity in the kernel. It’s tied to a specific driver and lives in
/sys/devices/. For your character device, each instance you create is represented by adeviceobject. - Class Device (Legacy): This is an older kernel structure (pre-2.6.26) that acted as a bridge between a
classand adevice. It was used to expose the device to userspace under the class’s/sys/class/directory. It’s deprecated now—modern kernels integrate this functionality directly into thedevicestructure, so you’ll only see this in older codebases. - Driver: The code that directly interacts with (or emulates) hardware to provide functionality. Your kernel module is essentially a driver for your custom character device. Drivers register with the kernel, bind to compatible
deviceinstances, and handle operations likeread()/write()for character devices.
Which Functions Create Device Nodes?
The process depends on which kernel version you’re targeting, since the API evolved:
Legacy Flow (pre-2.6.26)
- First, register your character device with
register_chrdev(). - Create a class with
class_create()to categorize your device. - Use
class_device_create(): this is the function that triggers userspace tools (udev/mdev) to create the corresponding/dev/device node. It links your device to the class, giving udev the info it needs to set up the node.
Modern Flow (2.6.26+)
class_device_create()was replaced bydevice_create()—this is the current function responsible for signaling userspace to create the/dev/node.- The typical flow is:
- (Optional, but more flexible) Use
alloc_chrdev_region(),cdev_init(), andcdev_add()instead ofregister_chrdev()to set up your character device. - Create a class with
class_create(). - Call
device_create(): this associates your device with the class, and udev automatically creates the/dev/node with the correct permissions and name.
- (Optional, but more flexible) Use
A quick note: If you skip these class/device functions, you’d have to manually create the device node with the mknod command in userspace. Using the kernel functions is the standard approach because it lets udev handle node creation dynamically, which is more robust and user-friendly.
内容的提问来源于stack exchange,提问作者Artium

