linux字符设备

  • 动态申请设备号

  • 静态申请设备号

  • cdev的结构体介绍

  • cdev_init () 结构体介绍

有了设备号后用cdev_init 函数初始化结构体

c 复制代码
/**
 * cdev_init() - initialize a cdev structure
 * @cdev: the structure to initialize
 * @fops: the file_operations for this device
 *
 * Initializes @cdev, remembering @fops, making it ready to add to the
 * system with cdev_add().
 */
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
{
	memset(cdev, 0, sizeof *cdev);
	INIT_LIST_HEAD(&cdev->list);
	kobject_init(&cdev->kobj, &ktype_cdev_default);
	cdev->ops = fops;
}
  • step3 cdev_add 函数设置

向系统添加一个cdev结构体

  • 参数1:添加cdev结构体
  • 参数2:添加设备号
  • 参数3:注册的设备个数
c 复制代码
/**
 * cdev_add() - add a char device to the system
 * @p: the cdev structure for the device
 * @dev: the first device number for which this device is responsible
 * @count: the number of consecutive minor numbers corresponding to this
 *         device
 *
 * cdev_add() adds the device represented by @p to the system, making it
 * live immediately.  A negative error code is returned on failure.
 */
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
{
	int error;

	p->dev = dev;
	p->count = count;

	if (WARN_ON(dev == WHITEOUT_DEV)) {
		error = -EBUSY;
		goto err;
	}

	error = kobj_map(cdev_map, dev, count, NULL,
			 exact_match, exact_lock, p);
	if (error)
		goto err;

	kobject_get(p->kobj.parent);

	return 0;

err:
	kfree_const(p->kobj.name);
	p->kobj.name = NULL;
	return error;
}

代码实现流程


卸载字符设备 通过modulecdec_exit() 函数实现

  • 先卸载设备号
  • 再进行cdev结构体的删除

makefile

  • 实现cdev设备的makefile

    obj -m += cdev.o
    KDIR :=/home/....(实际内核源码路径)
    PWD?= (shell pwd) all: make -C (KDIR) M =$(PWD) modules

    clean:
    rm -r *.ko *.mod.o *mod.c *symvers *.order

makefile 代码

相关推荐
米高梅狮子2 小时前
03.网络类服务实践
linux·运维·服务器·网络·kubernetes·centos·openstack
June`2 小时前
网络编程时内核究竟做了什么???
linux·服务器·网络
楼兰公子3 小时前
RK3588 + Linux7.0.3 网络工程调试错误速查手册
linux·网络·3588
Elnaij3 小时前
Linux系统与系统编程(9)——自设计shell与基础IO
linux·服务器
IMPYLH3 小时前
Linux 的 unexpand 命令
linux·运维·服务器·bash
|_⊙4 小时前
Linux 文件知识 补充
linux·运维·服务器
落羽的落羽5 小时前
【算法札记】练习 | Week4
linux·服务器·数据结构·c++·人工智能·算法·动态规划
Mortalbreeze5 小时前
深度理解文件系统 ---- 从磁盘存储到内核存储
大数据·linux·数据库
LN花开富贵8 小时前
Ubuntu aarch64 架构安装 NoMachine 远程控制 避坑与实战
linux·运维·笔记·学习·ubuntu·嵌入式
取经蜗牛8 小时前
Windows 11 WSL + Ubuntu 24.04 安装指南
linux·windows·ubuntu