Johannes 《Linux内核模块与设备驱动开发:编写Linux驱动程序》 (9)manual_cdev

视频教程:Lecture 9 - 手动创建字符设备_哔哩哔哩_bilibili

代码:anGitHub - Johannes4Linux/Linux_Driver_Tutorial: My new Tutorial how to get started with Linux Kernel Modules and Linux Drivers. Smtarted in 2024 · GitHub

复制代码
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>

static dev_t dev_nr;
static struct cdev my_cdev;

static ssize_t my_read(struct file *f, char __user *u, size_t l, loff_t *o)
{
	pr_info("hello_cdev - Read is called\n");
	return 0;
}


static struct file_operations fops = {
	.read = my_read
};

static int __init my_init(void)
{
	int status;
#ifdef STATIC_DEVNR
	dev_nr = STATIC_DEVNR;
	status = register_chrdev_region(dev_nr, MINORMASK + 1, "hello_cdev");
#else
	status = alloc_chrdev_region(&dev_nr, 0, MINORMASK + 1, "hello_cdev");
#endif
	if (status) {
		pr_err("hello_cdev - Error reserving the region of device numbers\n");
		return status;
	}

	cdev_init(&my_cdev, &fops);
	my_cdev.owner = THIS_MODULE;

	status = cdev_add(&my_cdev, dev_nr, MINORMASK + 1);
	if (status) {
		pr_err("hello_cdev - Error adding cdev\n");
		goto free_devnr;
	}

	pr_info("hello_cdev - Registered a character device for Major %d starting with Minor %d\n", MAJOR(dev_nr), MINOR(dev_nr));
	return 0;

free_devnr:
	unregister_chrdev_region(dev_nr, MINORMASK + 1);
	return status;
}

static void __exit my_exit(void)
{
	cdev_del(&my_cdev);
	unregister_chrdev_region(dev_nr, MINORMASK + 1);
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Johannes 4Linux");
MODULE_DESCRIPTION("A sample driver for manually registering a character device");

添加了头文件<linux/cdev.h>,

程序中调用的宏 :STATIC_DEVNR ,MINORMASK

手动注册字符设备:

status = register_chrdev_region(dev_nr, MINORMASK + 1, "hello_cdev");

register_chrdev_region 需要配置主/副设备号,这里用的 STATIC_DEVNR ,MINORMASK+1 来注册字符设备 hello_cdev

动态注册字符设备:

status = alloc_chrdev_region(&dev_nr, 0, MINORMASK + 1, "hello_cdev");

不需要手动配置,自动配置字符设备 hello_cdev

创建并添加字符设备:

cdev_init(&my_cdev, &fops);

&my_cdev 指向全局变量里这个指针,fops就将字符设备和读写操作结合起来

全局变量my_cdev 的所有者是这个模块,这样就将hello_cdev 接上了

my_cdev.owner = THIS_MODULE;

这样系统内核就添加字符设备,在 /proc/dev/中可以看到字符设备 hello_cdev,主设备号是dev_nr

status = cdev_add(&my_cdev, dev_nr, MINORMASK + 1);

不过这节系统内核添加hello_cdev这个设备驱动之后还是要mknod 创建字符设备 mknod /dev/hello0 c 236 0

相关推荐
无忧.芙桃1 小时前
Linux系统编程(四):用户与权限管理
linux·运维·服务器
谙弆悕博士4 小时前
多智能体架构详解:层级树状架构(分级主从型)
运维·架构·大模型·agent·多智能体·langgraph·层级树状
戊本菌4 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
aningx5 小时前
Arch 系用 greetd 实现开机自动进 Plasma Wayland,注销自动回桌面
linux
江无行者6 小时前
Linux 服务器 top 命令详解
linux
HMS工业网络6 小时前
工业远程访问的五项安全部署原则
运维·服务器·安全
吴建旭 智宅焕7 小时前
智能家居全国交付中执行端能力评估与分级调度架构设计:从注册数量到交付确定性的系统实现
运维·智能家居·devops
嵌入式 Linux手记8 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式
星恒随风8 小时前
MySQL 从零入门(九):事务管理详解——ACID、COMMIT、ROLLBACK、SAVEPOINT 与四种隔离级别
linux·服务器·数据库·笔记·mysql
草莓熊Lotso9 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构