注册一个字符设备驱动有两种方法:
1. int register_chrdev(unsigned int major, const char *namem , struct file operations *fopen);
它是一个旧的设备注册函数,在新的内核版本中已经被废弃。
major是设备的主设备号,name是驱动程序的名称,而fops是默认的file_operations结构(这是只限于file_operations结构)。
对于register_chrdev的调用将为给定的主设备号注册0-255作为次设备号,并为每个设备建 立一个对应的默认cdev结构。
register_chrdev()可以实现静态和动态注册两种方法,主要是通过判断给定的主设备号是否为0来进行区别,为0的时候为动态注册,否则静态注册。
register_chrdev_region以及alloc_chrdev_region就是将上述函数的静态和动态注册设备号进行了拆分,前者为静态注册,后者为动态注册。
2. void cdev_init(struct cdev *cdev, struct file_operations *fops)
该注册函数可以将cdev结构嵌入到自己的设备特定的结构中。cdev是一个指向结构体cdev的指针,而fops是指向一个类似于f file_operations结构(可以是file_operations结构,但不限于该结构)的指针。
#include <linux/fs.h>
#include <linux/cdev.h>
struct my_device {
// 设备特定的成员
int device_specific_data;
// ...
struct cdev cdev; // 嵌入的 cdev 对象
};