linux字符设备驱动

写linux驱动程序的一般步骤:

1.定义主设备号

2.构造并初始化file_operations结构体,提供read、write等函数供应用程序使用。

3.注册

4.声明出口函数和入口函数

5.支持的协议MODULE_LICENSE("GPL")

本篇文章记录字符设备的驱动框架:

1.定义cdev接口体和class结构体

#define HELLO_CNT 2

static int major = 0;//主设备号为0,需要让系统自动生成主设备号
static struct cdev hello_cdev;
static struct class *cls;
2.构造file_operations结构体
struct file_operations hello_fops = {
     .owner = THIS_MODULE,
     .open   = hello_open,
};
static int hello_open(struct inode *inode, struct file *file)
{
     printk("hello_open
");
     return 0;
}

3.注册

dev_t devid;
if (major) {
     /* 主设备号已确定 */
     devid = MKDEV(major, 0);
     register_chrdev_region(devid, HELLO_CNT, "hello");
} else {
     /* 主设备号为0,让系统自动为我们分配主设备号 */
     alloc_chrdev_region(&devid, 0, HELLO_CNT, "hello");
     major = MAJOR(devid);
}
cdev_init(&hello_cdev, &hello_fops);
cdev_add(&hello_cdev, devid, HELLO_CNT);
4.创建设备节点
cls = class_create(THIS_MODULE, "hello");
device_create(cls, NULL, MKDEV(major, 0), NULL, "hello0");// /dev/hello0
device_create(cls, NULL, MKDEV(major, 1), NULL, "hello1");// /dev/hello1
原文地址:https://www.cnblogs.com/zpehome/p/3811154.html