一、字符设备概述
Linux 系统中,设备被分为字符设备、块设备和网络设备等。字符设备以字节流的方式进行数据传输,数据的访问是按顺序的,一个字节一个字节地进行读取和写入操作,没有缓冲区。例如,终端(/dev/tty)、鼠标、键盘等设备都是典型的字符设备。
字符设备通过特殊的设备文件来表示。这些设备文件通常位于/dev
目录下。设备文件有主设备号(major number)和次设备号(minor number)。主设备号用于标识设备驱动程序,内核通过主设备号来查找对应的驱动程序;次设备号用于标识同一类型设备中的不同个体。例如,系统中可能有多个串口设备,它们的主设备号相同(表示使用相同的驱动程序),但次设备号不同,用于区分不同的串口。
二、字符设备驱动开发
1、驱动文件
//添加头文件
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ide.h>
static char readbuf[100]; // 读缓冲区
static char writebuf[100]; // 写缓冲区
static char message[] = {
"This message comes from kernel."};
static int drive_major; //设备号
static struct class *KernelPrint_cls;
//1.5.5 驱动程序的打开,读取,写入,关闭。
static int KernelPrint_open(struct inode *inode, struct file *filp) //打开函数
{
//本DEMO无需申请资源,此处留白
printk("-KernelPrint open-\n");
return 0;
}
static ssize_t KernelPrint_read(struct file *filp, char __user *buf, size_t count, loff_t *fops) //用户读取,内核发送信息
{
int flag = 0;
memcpy(readbuf, message, sizeof(message)); //使用memcpy将内核中要发送的内容写入读缓冲区
flag = copy_to_user(buf, readbuf, count); //使用copy_to_user函数将读缓冲区的内容发送到用户态
if (flag == 0) //返回0成功,否则失败
{
printk("Kernel send data success!\n");
}
else
{