07_linux 字符设备了解

1. 创建字符设备之前,需要先申请字符设备id

int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
功能:向内核申请设备号
参数:
dev:保存内核给你分配的设备号,注意:主设备号就一个,其中的次设备号是起始的次设备号
baseminor:希望起始的次设备号,一般给0
count:次设备号的个数, 例如:count=4并且baseminor=0, 则次设备号:0,1,2,3
name:设备名称(不是设备文件名,两码事), 主要用于调试:执行cat /proc/devices能够看到申请的设备号信息

void unregister_chrdev_region(dev_t from, unsigned count)
功能:释放设备号资源
from:传递之前申请的设备号
count:次设备号的个数

2. 

对应的头文件:include/linux/fs.h
对应的源文件:fs/char_dev.c

cat /proc/devices //查看申请到的主设备号

案例:加载驱动,申请设备号,卸载驱动,释放设备号

 3. 字符设备创建和使用的接口

include/linux/fs.h
struct file_operations {
struct module *owner;
ssize_t (*read) (struct file *file, char __user *buf, size_t count, loff_t *ppos);
ssize_t (*write) (struct file *file, const char __user *buf,  size_t count,  loff_t *ppos);
int (*open) (struct inode *, struct file *);
int (*release) (struct inode *, struct file *);
long (*unlocked_ioctl) (struct file *file, unsigned int cmd, unsigned long buf); 

};

include/linux/cdev.h

struct cdev {};
void cdev_init(struct cdev *, const struct file_operations *);
int cdev_add (struct cdev *, dev_t, unsigned);
void cdev_del (struct cdev *);

 

include/linux/uaccess.h

int copy_from_user(void *to, const void __user *from, int n);
int copy_to_user(void __user *to, const void *from, int n);

posted @ 2025-06-01 09:33  靖意风  Views(12)  Comments(0)    收藏  举报