查看设备号
查看设备类
一、设备号申请:(cdev.h)
1静态申请:
dev_t from = MKDEV(major,minor);
int register_chrdev_region(dev_t from, unsigned count, const char *name)
2动态申请:int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name)
二、如何往内核添加一个cdev
struct cdev {
struct kobject kobj;
struct module *owner;
const struct file_operations *ops;
struct list_head list;
dev_t dev;
unsigned int count;
};
1.cdev_init()//注册字符设备
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
2.cdev_add();//添加到内核
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
3.cdev_del();//卸载
void cdev_del(struct cdev *p)
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
{
p->dev = dev;
p->count = count;
return kobj_map(cdev_map, dev, count, NULL, exact_match, exact_lock, p);
}
//设备结构体:struct cdev *p
//设备号:dev_t dev;
//设备数:unsigned count;
2)操作函数集合(头文件linux/fs.h)
结构体
struct file_operations cdd_fops={
.owner = THIS_MODULE;
.open = cdd_open,
.read = cdd_read,
.write = cdd_write,
.release = cdd_release,
}
实现cdd_fops的函数
- cdd_open实现:
.open函数原型:
int (*open) (struct inode *, struct file *);
cdd_read实现:
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
cdd_write实现:
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
cdd_release实现:
.release函数原型:
ssize_t release(struct inode *inode, struct file *filp)
三、设备类class的添加(头文件device.h)
//定义class指针
struct class *cdd_class;
//创建
struct class *class_create(owner,name);
owner:THIS_MODULE;
name:设备类的名字;
//销毁
class_destroy(struct class *cls);
四、设备文件节点
struct device *cdd_device;//定义一个device指针
//创建
struct device *device_create(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, .