1,这本书是以scull 为例子来介绍字符设备驱动程序的编写的。
scull是一个操作内存区域的字符设备驱动程序。
2,注册设备号的获取、注销及注册
@获取dev_t 类型设备号
设备在内核中以dev_t 类型保存主次设备号的。用MKDEV(major,minor) 来获得dev_t 类型的设备号,相反,用MAJOR(dev_t dev) 转换主设备号,MINOR(dev_t dev) 转换出次设备号。
@内核分配设备号
int register_chrdev_region(dev_t dev,1,char *name);
@自动分配
int alloc_chrdev_region(dev_t *dev ,0,1,char *name);
@注销
void unregister_chrdev_region(dev,1);
@注册模板
static void key_setup_cdev(struct cdev *dev,int major,struct file_operations *fops)
{
int err,devno=MKDEV(dev,0);
cdev_init(dev,fops);
dev->owner = THIS_MODULE;
dev->ops = fops;
err=cdev_add(dev,devno,1); //向内核中添加
if (err)
printk (KERN_NOTICE "Error %d adding key%d", err, minor);
}
-------------
获得设备号的模板
static int __init userkey_init(void)
{
int result;
dev_t dev=MKDEV(major,o);
char dev_name[]="key";
if(key_major)
result=register_chrdev_region(major,1,dev_name);//分配设备号
else{
result=alloc_chrdev_region(*dev,0,1,dev_name);//自动分配
key_major=MAJOR(dev);//将dev_t 类型转换成主设备号
}
if (result < 0) {
printk(KERN_WARNING "key: unable to get major %d\n", key_major);
return result;
}
if (key_major == 0)
key_major = result;
/* 获取、分配设备号后要调用key_setup_cdev 注册 */
key_setup_cdev(&key_cdev, 0, &key_fops);
}
3,open、write、read、release函数
4,三个设备驱动程序中重要的结构体:file_operations, file ,inode
struct file_operations key_fops={
.owner =THIS_MODULE,
.open = key_open,
.read = key_read,
.release=key_close,
};
5,头文件#include<linux/cdev.h>
void cdev_init(); void cdev_add(); void cdev_del();
#include<asm/kernel.h> //内核代码与用户空间移动数据
unsigned long copy_to_user(void *to,const void *from,uint count);
例如:copy_to_user(buff, &key_values, sizeof(key_values));
unsigned long copy_from_user();