命令:lsmod —— 查看当前内核中加载了那些模块
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#define BASEMINOR 0
#define COUNT 3
#define NAME "cdev_demo"
dev_t devno = 0;
struct cdev *cdevp = NULL;
int demo_open(struct inode *inode, struct file *filp)
{
printk(KERN_DEBUG "---%s---%s---%d---\n",__FILE__,__func__,__LINE__);
return 0;
}
int demo_release(struct inode *inode, struct file *filp)
{
printk(KERN_DEBUG "---%s---%s---%d---\n",__FILE__,__func__,__LINE__);
return 0;
}
struct file_operations fops = {
.owner = THIS_MODULE,
.open = demo_open,
.release = demo_release,
};
int __init demo_init(void)
{
int ret = 0;
//0.申请设备号-内核分配主设备号,次设备好从0开始,共三个(0,1,2)
ret = alloc_chrdev_region(&devno,BASEMINOR,COUNT, NAME);
if(ret < 0){
printk(KERN_ERR "alloc_chrdev_region failed...\n");
goto err0;
}
printk(KERN_INFO "---major:%d---\n",MAJOR(devno));
//1.分配cdev结构体
cdevp = cdev_alloc();
if(cdevp == NULL){
printk(KERN_ERR "cdev_alloc failed...\n");
ret = -ENOMEM;
goto err1;
}
//2.初始化cdev结构体
cdev_init(cdevp, &fops);
//3.将cdev结构体添加到内核中,由内核对驱动进行统一的管理
ret = cdev_add(cdevp, devno, COUNT);
if(ret < 0){
printk(KERN_ERR "cdev_add failed...\n");
goto err1;
}
printk(KERN_DEBUG "---%s---%s---%d---\n",__FILE__,__func__,__LINE__);
return 0;
err1:
unregister_chrdev_region(devno, COUNT);
err0:
return ret;
}
void __exit demo_exit(void)
{
cdev_del(cdevp);
unregister_chrdev_region(devno, COUNT);
printk(KERN_DEBUG "---%s---%s---%d---\n",__FILE__,__func__,__LINE__);
}
module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");