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

相关推荐
zmsup1 小时前
Agent 上下文调优:结合 OpsArk 运维智能体,设计模型每一步真正需要的信息
运维·agent·上下文压缩·运维智能体·上下文调优
gwf2162 小时前
Completion Queue(CQ)与中断处理:轮询、中断聚合与错误码 —— 面向AI集群的驱动级深度剖析
驱动开发·性能调优·pcie·rdma·ai集群·中断聚合·cq
DYWorker0012 小时前
Linux驱动:RK3568 GMAC + YT8531C 千兆以太网全流程解剖
linux
吴声子夜歌3 小时前
Nginx应用与运维——Nginx负载均衡应用实战(二)
运维·nginx·负载均衡
lisanmengmeng3 小时前
NRPE 添加命令(一)
linux·运维·服务器
pt10433 小时前
CML网络仿真入门-2:使用CML模拟网络实验环境
运维·网络协议
树下水月4 小时前
Typora破解
linux·服务器·前端
沫璃染墨5 小时前
《从零入门Linux系统篇(五十七):线程篇·十——生产者消费者模型进阶:从环形缓冲区到POSIX信号量》
linux·运维·服务器·开发语言·c++·系统架构·信号处理
wuminyu5 小时前
LockStack在虚拟线程Mount和Unmount拷贝过程剖析
java·linux·c语言·jvm·c++
深念Y5 小时前
rime-雾凇拼音-配置记录
linux·junit·软件·拼音·kde