驱动框架
#include <linux/module.h> #include <linux/moduleparam.h> #include <linux/fs.h> #include <linux/cdev.h> //定义一个字符设备对象 struct cdev *cdev; dev_t dev; unsigned int baseminor = 0; unsigned int count = 1; const char * name = "demochar"; //向上层提供的接口 //向下层操作硬件----在接口里去操作硬件 const struct file_operations fops = { }; static int __init demo_init(void) { int retval; printk("----%s---%d.\n",__func__,__LINE__); //1、为字符设备分配空间 cdev = cdev_alloc(); if(cdev == NULL){ printk("cdev_alloc faild.\n"); return -ENOMEM; } //2、初始化字符设备 cdev_init(cdev,&fops); //3、动态申请设备号存储在dev内 retval = alloc_chrdev_region(&dev, baseminor, count, name); if(retval){ printk("alloc_chrdev_region faild.\n"); goto err0; } printk("major :%d.\n",MAJOR(dev)); //4、添加到内核 retval = cdev_add(cdev, dev, count); if(retval){ printk("cdev_add failed.\n"); goto err1; } //5、硬件初始化 return 0; err1: unregister_chrdev_region(dev, count); err0: return retval; } static void __exit demo_exit(void) { printk("----%s---%d.\n",__func__,__LINE__); cdev_del(cdev); unregister_chrdev_region(dev, count); } //入口函数 module_init(demo_init); //出口函数 module_exit(demo_exit); //GPL许可协议 MODULE_LICENSE("GPL");