so2学习日志3-字符设备


设备注册/销毁入口

1
2
module_init(so2_cdev_init);
module_exit(so2_cdev_exit);

在注册函数中,进行设备的初始化,包括设备号,原子变量等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
static int so2_cdev_init(void)
{
int err;
int i;

/* TODO 1: register char device region for MY_MAJOR and NUM_MINORS starting at MY_MINOR */
register_chrdev_region(MKDEV(MY_MAJOR, MY_MINOR), NUM_MINORS, MODULE_NAME);

for (i = 0; i < NUM_MINORS; i++) {
/*TODO 4: initialize buffer with MESSAGE string */
strcpy(devs[i].buffer, MESSAGE);
/* TODO 3: set access variable to 0, use atomic_set */
atomic_set(&devs[i].access, 0);
/* TODO 2: init and add cdev to kernel core */
cdev_init(&devs[i].cdev, &so2_fops);
cdev_add(&devs[i].cdev, MKDEV(MY_MAJOR, MY_MINOR + i), 1);
}

return 0;
}

注销函数同理

1
2
3
4
5
6
7
8
9
10
static void so2_cdev_exit(void)
{
int i;
for (i = 0; i < NUM_MINORS; i++) {
/* TODO 2: delete cdev from kernel core */
cdev_del(&devs[i].cdev);
}
/* TODO 1: unregister char device region, for MY_MAJOR and NUM_MINORS starting at MY_MINOR */
unregister_chrdev_region(MKDEV(MY_MAJOR, MY_MINOR), NUM_MINORS);
}