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

相关推荐
乌托邦的逃亡者16 分钟前
CentOS/Openeuler主机中,为一个网卡设置多个IP地址
linux·运维·网络·tcp/ip·centos
念恒123061 小时前
进程控制---自定义Shell
linux·c语言
风曦Kisaki2 小时前
# Linux Shell 编程入门 Day02:条件测试、if 判断、循环与随机数
linux·运维·chrome
李日灐2 小时前
< 6 > Linux 自动化构建工具:makefile 详解 + 进度条实战小项目
linux·运维·服务器·后端·自动化·进度条·makefile
嵌入式×边缘AI:打怪升级日志2 小时前
嵌入式Linux开发:开源组件、第三方库与许可证详解
linux
计算机安禾2 小时前
【Linux从入门到精通】第34篇:搭建FTP与Samba——跨平台文件共享解决方案
linux·运维·服务器
日取其半万世不竭2 小时前
用 Netdata 实时监控服务器,比 Prometheus + Grafana 轻量得多
linux·服务器·网络·系统架构·负载均衡·zabbix·grafana
jamon_tan3 小时前
Linux下cmake构建方法
linux
JiaWen技术圈3 小时前
内核子系统 nf_tables 深度解析
linux·服务器·安全·运维开发
计算机安禾3 小时前
【Linux从入门到精通】第32篇:Nginx入门——高性能Web服务器搭建
linux·服务器·nginx