class_create(),device_create解析.device_create和device_add区别

提醒一点,udev是应用层的,不要试图在内核的配置选项里找到它;加入对udev的支持很简单,以作者所写的一个字符设备驱动为例,在驱动初始化的代码里调用class_create为该设备创建一个class,再为每个设备调用device_create创建对应的设备。大致用法如下:

       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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值