Linux驱动----2、字符设备驱动

这篇博客深入探讨了Linux字符设备驱动,重点介绍了设备号在区分设备和驱动程序中的作用。同时,讲解了在内核空间中如何通过file_operations结构将驱动操作与设备号关联。还提到了file结构和inode结构在文件表示中的差异,以及在open、release和close操作中的行为。此外,文章讨论了字符设备的注册过程,并阐述了scull设备在内存使用方面的特点。
摘要由CSDN通过智能技术生成

1.设备号

对字符设备的访问通过文件系统内的设备名称进行,这些名称也称为文件系统树的节点,位于/dev下。主设备号标志着设备对应的驱动程序,次设备号区分相同驱动程序下的不同设备。

dev_t dev;//由主次设备号构成

MAJOR(dev_t dev); //得到主设备号
MINOR(dev_t dev);
MKDEV(int major, int minor);//合成
//静态分配设备号, first是主次设备号的合成, count是次设备号个数, name是与该范围编号关联的设备名称
//它将出现在/proc/devices和sysfs中
int register_chrdev_region(dev_t first, unsigned int count, char *name);

//动态分配设备号, 分配到的设备号返回给参数dev, firstminor是要申请的第一个次设备号
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *name)

当编译好模块*.ko文件后,需要安装该模块, 并在/dev下创建设备文件(mknod 模块名)。用户可以在rc.local文件中调用如下 脚本。

#!/bin/sh
module="simple"
device="simple"
mode="664"

# Group: since distributions do it differently, look for wheel or use staff
if grep '^staff:' /etc/group > /dev/null; then
    group="staff"
else
    group="wheel"
fi

# invoke insmod with all arguments we got
# and use a pathname, as newer modutils don't look in . by default
#$*表示从命令行传入的所有参数在insmod *.ko时传入
/sbin/insmod -f ./$module.ko $* || exit 1

#awk命令格式:如果符合pattern则执行后面的action,这里/proc/devices下每行由主设备号和设备名称构##成,$2指设备名称, $1指设备号;
#awk "\$2==\"mdp\" {print \$1}" /proc/devices 即获得mdp的设备号
major=$(awk "\$2==\"$module\" {print \$1}" /proc/devices)  
# Remove stale nodes and replace them, then give gid and perms
# Usually the script is shorter, it's simple that has several devices in it.

rm -f /dev/${device}[rn]
mknod /dev/${device}r c $major 0
mknod /dev/${device}n c $major 1
chgrp $group /dev/${device}[rn] 
chmod $mode  /dev/${device}[rn]

重要的数据结构

file_operations, 定义在linux/fs.h中用来把驱动程序操作连接到设备号。

file 其和用户空间的FI

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值