|
这是我的代码,加上cdev_add和cdev_del之后,rmmod这个模块,会造成内核崩溃。
这应该是一个经典的例子,每个学内核人的必经之路。 我却卡在这里了。
大侠们帮忙看看,谢谢;
include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/cdev.h>
dev_t scull_dev_num = 0;
int major = 0;
int minor = 0;
int cdev_registered = 0;
struct scull_mem{
void *data;
struct scull_mem *next;
};
struct scull_dev{
struct cdev cdev;
unsigned long size;
struct scull_mem *data;
} *dev;
struct file_operations scull_ops={
.owner=THIS_MODULE,
};
void cleanup(void)
{
if(cdev_registered)
{
cdev_del(&dev->cdev);
cdev_registered = 0;
}
if(dev != NULL)
{
kfree(dev);
dev = NULL;
}
if (scull_dev_num != 0)
{
unregister_chrdev_region(scull_dev_num, 1);
scull_dev_num = 0;
}
}
static int __init scull_init(void)
{
int retval = 0;
if ((retval = alloc_chrdev_region(&scull_dev_num, 0, 1, "scull")) < 0)
{
printk("<1>alloc_chrdev_region < 0\n");
cleanup();
return 0;
}
major = MAJOR(scull_dev_num);
minor = MINOR(scull_dev_num);
if ((dev = kmalloc(sizeof(struct scull_dev), GFP_KERNEL)) == NULL)
{
printk("<1>kmalloc failed \n");
cleanup();
return -ENOMEM;
}
dev->size = 0;
dev->data = NULL;
cdev_init(&dev->cdev, &scull_ops);
dev->cdev.owner = THIS_MODULE;
dev->cdev.ops = &scull_ops;
if((retval = cdev_add(&dev->cdev, scull_dev_num, 1)) < 0)
{
printk("<1>cdev_add failed\n");
cleanup();
return retval;
}
cdev_registered = 1;
return 0;
}
static void __exit scull_exit(void)
{
cleanup();
printk(KERN_ALERT "Scull cleanuped!\n");
}
module_init(scull_init);
module_exit(scull_exit);
MODULE_LICENSE("GPL"); |
|