At the beginning of writing Linux Device driver , A lot of times utilize mknod Command to manually create a device node , actually Linux The kernel provides us with a set of functions , Can be used to When the module is loaded, it is automatically in /dev Create the corresponding device node under the directory , And delete the node when unloading the module , Of course, the prerequisite is that user space is migrated udev.
The kernel defines struct class Structure , seeing the name of a thing one thinks of its function , One struct class A structure type variable corresponds to a class , The kernel also provides class_create(…) function , You can use it to create a class , This class is stored in sysfs below , Once the class is created , Call again device_create(…) Function in the /dev Create the corresponding device node under the directory . such , When loading a module , In user space udev Will automatically respond device_create(…) function , Go to /sysfs Find the corresponding class under to create the device node .
Be careful , stay 2.6 In earlier kernel versions ,device_create(…) Different function names , yes class_device_create(…), So when compiling the previous module program in the new kernel, sometimes an error will be reported , Because the function names are different , And there are some changes in the parameter settings .
struct class and device_create(…) as well as device_create(…) It's all defined in /include/linux/device.h in , You must include this header file when using it , Otherwise, the compiler will report an error .