特别声明
从第二个驱动程序开始(https://blog.youkuaiyun.com/wenhao_ir/article/details/144973219),直接用函数register_chrdev
打包完成了本博文中进行驱动注册的前几个步骤,所以这篇博文只作为了解Linux的驱动注册的过程,真正的工作中建议使用函数register_chrdev
。
准备工作
先把Linux的源码导入代码阅读编辑器中【如果你对驱动开发中涉及到的结构体都比较熟悉,其实不一定要导入】。详情见 https://blog.youkuaiyun.com/wenhao_ir/article/details/144871074
建议先阅读的博文
然后最好先读一下我写的关于嵌入式Linux驱动开发的基本知识的两篇博文,链接 https://blog.youkuaiyun.com/wenhao_ir/article/details/144888989
https://blog.youkuaiyun.com/wenhao_ir/article/details/144901797
任务需求
完整驱动程序源代码
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
/* 1. 定义主设备号存储变量major */
static int major = 0;
// 初始化描述设备实例信息的核心结构体 cdev hello_cdev
static struct cdev hello_cdev;
static char kernel_buf[1024];
static struct class *hello_class;
#define MIN(a, b) (a < b ? a : b)
/* 3. 实现对应的open/read/write等函数,填入file_operations结构体 */
static ssize_t hello_drv_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
int err;
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
err = copy_to_user(buf, kernel_buf, MIN(1024, size));
return MIN(1024, size);
}
static ssize_t hello_drv_write (struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
int err;
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
err = copy_from_user(kernel_buf, buf, MIN(1024, size));
return MIN(1024, size);
}
static int hello_drv_open (struct inode *node, struct file *file)
{
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
static int hello_drv_close (struct inode *node, struct file *file)
{
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
/* 2. 定义自己的file_operations结构体 */
static struct file_operations hello_drv = {
.owner = THIS_MODULE,
.open = hello_drv_open,
.read = hello_drv_read,
.write = hello_drv_write,