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 代码

相关推荐
一叶龙洲5 小时前
wslg打开Ubuntu24.04默认打开图形界面
linux·服务器·数据库·ubuntu
敖行客 Allthinker7 小时前
Parallels Ubuntu虚拟机项目如何让手机访问?完整解决方案
linux·运维·ubuntu
keyipatience8 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
j7~8 小时前
【Linux】二十二.《Linux 信号机制完全指南:表示、捕捉与处理》
linux·信号处理·volatile·可入重函数·保存信号
观山岳五楼9 小时前
Ubuntu 24 怎么使用Ubuntu 20 的镜像源
linux·运维·ubuntu
m0_7156467610 小时前
20260720
linux·arm
寒晓星10 小时前
[linux]线程及多线程
linux·运维
辰痕~10 小时前
物理机装Linux操作系统(Ubuntu为例)
linux·ubuntu
国服第二切图仔12 小时前
13其他工具 - Skill/LSP/Sleep等
linux·运维·里氏替换原则
就不掉头发12 小时前
计算机的虚拟内存
linux·服务器·windows