在 Linux 2.6 的版本中,用 dev_t 类型来描述设备号(dev_t 是 32 位数值类型,其中高 12 位表示主设备号,低 20 位表示次设备号)。用两个宏 MAJOR 和 MINOR分别获得 dev_t 设备号的主设备号和次设备号,而且用 MKDEV 宏来实现逆过程,即组合主设备号和次设备号而获得 dev_t 类型设备号。
申请设备号
int register_chrdev_region(dev_t first, unsigned int count, char *name);//手工申请
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *nam );//自动申请
释放设备号
void unregister_chrdev_region(dev_t first, unsigned int count);
参数传入:
first:要分配的设备号的初始值
count:要分配(释放)的设备号数目
name:要申请设备号的设备名称(在/proc/devices和 sysfs 中显示)
dev:动态分配的第一个设备号
*********************************************************************************************
注册注销函数
#include<linux/cdev.h>
sturct cdev *cdev_alloc(void); /*动态申请一个cdev内存*/
void cdev_init(struct cdev *cdev, struct file_operations *fops);/*初始化已分配的cdev,建立cdev与 file_operations的连接*/
int cdev_add (struct cdev *cdev, dev_t first,unsigned int count); /*向系统添加cdev,完成字符设备的注册,通常在模块加载时调用*/
void cdev_del(struct cdev *dev);/*向系统删除cdev,完成字符设备的注销,通常在模块卸载时调用*/
参数传入:
cdev :需要初始化 / 注册 / 删除的struct cdev 结构
fops :该字符设备的file_operations 结构
first:要分配的设备号的初始值
count:要分配(释放)的设备号数目