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 */