1、驱动模块的加载和卸载
/* 驱动入口函数 */
static int __init xxx_init(void)
{
/* 入口函数具体内容 */
int retvalue = 0;
/* 注册字符设备驱动 */
retvalue = register_chrdev(200, "chrtest", &test_fops);
if(retvalue < 0){
/* 字符设备注册失败,自行处理 */
}
return 0;
}
/* 驱动出口函数 */
static void __exit xxx_exit(void)
{
/* 出口函数具体内容 */
/* 注销字符设备驱动 */
unregister_chrdev(200, "chrtest");
}
module_init(xxx_init);//注册模块加载函数
module_exit(xxx_exit);//注册模块卸载函数
2、字符设备注册与注销
函数原型
static inline int register_chrdev(unsigned int major,const char *name,
const struct file_operations *fops);
static inline void unregister_chrdev(unsigned int major,const char*name);
/*
major:主设备号
name:设备名字,指向一串字符串
fops:结构体 file_operations 类型指针
*/
函数一般运用驱动模块的入口函数和出口函数 如上。
3、实现设备的具体操作函数
file_operations 结构体就是设备的具体操作函数。
static struct file_operations test_fops = {
.owner = THIS_MODULE,
.open = chrtest_open,
.read = chrtest_read,
.write = chrtest_write,
.release = chrtest_release,
};
加入设备操作函数:
/* 打开设备 */
static int chrtest_open(struct inode *inode, struct file *filp)
{
/* 用户实现具体功能 */
return 0;
}
/* 从设备读取 */
static ssize_t chrtest_read(struct file *filp, char __user *buf,size_t cnt, loff_t *offt)
{
/* 用户实现具体功能 */
return 0;
}
/* 向设备写数据 */
static ssize_t chrtest_write(struct file *filp,const char __user *buf,size_t cnt, loff_t *offt)
{
/* 用户实现具体功能 */
return 0;
}
/* 关闭/释放设备 */
static int chrtest_release(struct inode *inode, struct file *filp)
{
/* 用户实现具体功能 */
return 0;
}
4、添加 LICENSE 和作者信息
MODULE_LICENSE("GPL");//使用GPL协议
MODULE_AUTHOR("wangcan");
MODULE_INFO(inttree, "Y");