driver c文件:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/err.h>
#define MMAP_DEV_NAME "mmapdev"
static dev_t mmap_dev_no = 0;
static struct cdev mmap_dev_cdev;
static struct class *mmap_dev_cls;
static struct device *mmap_device;
static struct file_operations mmapdrv_fops =
{
.owner = THIS_MODULE,
};
static int __init mmapdrv_init(void)
{
int ret = -1;
printk("mmapdrv init...\n");
ret = alloc_chrdev_region(&mmap_dev_no,0,1,MMAP_DEV_NAME);
if(ret < 0)
{
printk("alloc mmap dev no fail!\n");
return ret;
}
cdev_init(&mmap_dev_cdev,&mmapdrv_fops);
mmap_dev_cdev.owner = THIS_MODULE;
ret = cdev_add(&mmap_dev_cdev,mmap_dev_no,1);
if(ret != 0)
{
printk("cdev add faild!\n");
goto cdev_add_err;
}
#if 1
mmap_dev_cls = class_create(THIS_MODULE, MMAP_DEV_NAME);
if(IS_ERR(mmap_dev_cls))
{
printk("class create failed!\n");
goto cdev_class_err;
}
mmap_device = device_create(mmap_dev_cls,NULL,mmap_dev_no,NULL,MMAP_DEV_NAME);
if(IS_ERR(mmap_device))
{
printk("device create failed!\n");
goto device_create_err;
}
#endif
return 0;
device_create_err:
class_destroy(mmap_dev_cls);
cdev_class_err:
cdev_del(&mmap_dev_cdev);
cdev_add_err:
unregister_chrdev_region(mmap_dev_no,1);
return ret;
}
static void __exit mmapdrv_exit(void)
{
printk("mmapdrv exit...\n");
device_destroy(mmap_dev_cls,mmap_dev_no);
class_destroy(mmap_dev_cls);
cdev_del(&mmap_dev_cdev);
unregister_chrdev_region(mmap_dev_no,1);
}
module_init(mmapdrv_init);
module_exit(mmapdrv_exit);
MODULE_LICENSE("GPL");
Makefile 文件:
obj-m:=mmap_driver.o
PWD:=$(shell pwd)
KERNELDIR:=/lib/modules/$(shell uname -r)/build
all:
make -C $(KERNELDIR) M=$(PWD) modules
clean:
@rm -rf *.o *.mod.c *.mod.o *.ko *.order *.symvers .*cmd .tmp_versions *.mod
|