Linux 新的字符设备注册方法


1、定义字符设备结构体test_cdev
 
1 struct cdev { 
2 struct kobject kobj; 
3 struct module *owner; 
4 const struct file_operations *ops; 
5 struct list_head list; 
6 dev_t dev; 
7 unsigned int count; 
8 };
struct cdev test_cdev;

2、使用 cdev_init 函数对test_cdev初始化
cdev_init 函数原型如下
void cdev_init(struct cdev *cdev, const struct file_operations *fops)

示例代码

1 struct cdev testcdev; 
2 
3 /* 设备操作函数 */
4 static struct file_operations test_fops = { 
5 .owner = THIS_MODULE, 
6 /* 其他具体的初始项 */
7 };
8 
9 testcdev.owner = THIS_MODULE;
10 cdev_init(&testcdev, &test_fops); /* 初始化 cdev 结构体变量 */


3、使用cdev_add 函数Linux 系统添加test_cdev

cdev_add 函数用于向 Linux 系统添加字符设备
(cdev 结构体变量),首先使用 cdev_init 函数完成对 cdev 结构体变量的初始化,然后使用 cdev_add 函数向 Linux 系统添加这个字符设备。

cdev_add
函数原型如下:

int cdev_add(struct cdev *p, dev_t dev, unsigned count)


示例代码

1 struct cdev testcdev; 
2 
3 /* 设备操作函数 */
4 static struct file_operations test_fops = {
5 .owner = THIS_MODULE, 
6 /* 其他具体的初始项 */
7 };
8 
9 testcdev.owner = THIS_MODULE;
10 cdev_init(&testcdev, &test_fops); /* 初始化 cdev 结构体变量 */
11 cdev_add(&testcdev, devid, 1); /* 添加字符设备 */


4、使用cdev_del 函数删除test_cdev

卸载驱动的时候要使用 cdev_del
函数从 Linux 内核中删除相应的字符设备

void cdev_del(struct cdev *p)


示例代码

1 cdev_del(&testcdev); /* 删除 cdev */



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值