14、在总线下注册设备实验 *
我们成功地注册了自定义的总线, 并确保该总线已被系统识别和管理。 现在,将继续构建在该总线上注册设备的流程。
一、实验程序
C++
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/configfs.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/device.h>
#include <linux/sysfs.h>
extern struct bus_type mybus;
void myrelease(struct device *dev)
{
printk("This is myrelease\n");
};
struct device mydevice = {
.init_name = "mydevice", // 设备的初始化名称
.bus = &mybus, // 所属总线
.release = myrelease, // 设备的释放回调函数
.devt = ((255 << 20 | 0)), // 设备号
};
// 模块的初始化函数
static int device_init(void)
{
int ret;
ret = device_register(&mydevice); // 注册设备
return 0;
}
// 模块退出函数
static void device_exit(void)
{
device_unregister(&mydevice); // 取消注册设备
}
module_init(device_init); // 指定模块的初始化函数
module_exit(device_exit); // 指定模块的退出函数
MODULE_LICENSE("GPL"); // 模块使用的许可证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
二、运行
驱动加载之后, 我们进入/sys/devices 目录下, 有注册生成的设备。
我们进入到/sys/bus/mybus/devices 目录下, 在总线下注册的设备为 mydevice。