Linux驱动学习之第一个驱动程序(HelloWorld-最简单的字符型设备驱动程序-不设计具体的硬件的驱动程序)

特别声明

从第二个驱动程序开始(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,
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值