struct class *myclass ;
class_create(THIS_MODULE, “my_device_driver”);
device_create(myclass, NULL, MKDEV(major_num, minor_num), NULL, “my_device”);
这样的module被加载时,udev daemon就会自动在/dev下创建my_device设备文件。
我们在刚开始写Linux设备驱动程序的时候,很多时候都是利用mknod命令手动创建设备节点,实际上Linux内核为我们提供了一组函数,可以用来在模块加载的时候自动在 /dev目录下创建相应设备节点,并在卸载模块时删除该节点,当然前提条件是用户空间移植了udev。
内核中定义了struct class结构体,顾名思义,一个struct class结构体类型变量对应一个类,内核同时提供了class_create(…)函数,可以用它来创建一个类,这个类存放于sysfs下面,一旦创建好了这个类,再调用device_create(…)函数来在/dev目录下创建相应的设备节点。这样,加载模块的时候,用户空间中的udev会自动响应 device_create(…)函数,去/sysfs下寻找对应的类从而创建设备节点。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
网友问题:
device_create和device_add的区别:
device_create() 创建一个设备并注册到内核驱动架构...
device_add() 注册一个设备到内核,,少了一个创建设备..
是不是说调用device_create会在/dev/目录下创建结点,device_add不会。
精彩答复:
device_create | + -- kzalloc struct device | +---device_register | +-----device_initialize | +-----device_add device_create比device_add多做的事情非常清楚了呀。多一: 1. 新建struct device, device_add是不会新建的,只会加。 2. 进行了初始化, 如果不调device_register, 就得自己去调用device_initiali初始化。 关于第二点,device_register的函数说明说得很清楚: /** * device_register - register a device with the system. * @dev: pointer to the device structure * * This happens in two clean steps - initialize the device * and add it to the system. The two steps can be called * separately, but this is the easiest and most common. * I.e. you should only call the two helpers separately if * have a clearly defined need to use and refcount the device * before it is added to the hierarchy. */ 关于正真设备文件的创建(不是指sys下的文件), 最终是由device_add函数里头的kobject_uevent(&dev->kobj, KOBJ_ADD)完成的对hotplug_helper的调用的。 如果想了解uevent的详情,可以阅读《Linux设备模型浅析之uevent篇》或者他的一系列文章。 http://wenku.baidu.com/link?url= ... 6uL6GDxuKlOn41H7u77 |