如下代码可运行,总是会导致内核崩溃:
基于2.6内核 CentOS5.5
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
uint led_major =0 ,led_minor = 0;
dev_t led_dev_no;
module_param(led_major,uint,S_IWUGO);
struct cdev led_cdev;
static struct class *dev_class = NULL;
static struct device *dev_device = NULL;
static int leddev_open(struct inode *inode, struct file *file)
{
printk("ledev_open\n");
return 0;
}
static ssize_t leddev_read(struct file *file,char __user *userbuf,size_t count, loff_t *ppos)
{
printk("leddev_read\n");
return 0;
}
static ssize_t leddev_write(struct file *file, const char __user *buffer,size_t size, loff_t *ppos)
{
printk("leddev_write\n");
return 0;
}
static int leddev_close(struct inode *inode, struct file *file)
{
printk("leddev_close\n");
return 0;
}
struct file_operations leddev_fops =
{
.owner = THIS_MODULE,
.open = leddev_open,
.read = leddev_read,
.write = leddev_write,
.release = leddev_close
};
static int __init leddev_init(void)
{
int result;
led_dev_no= MKDEV(led_major,led_minor);
if(led_major)
{
result = register_chrdev_region(led_dev_no,1,"leddev");
}
else
{
result = alloc_chrdev_region(&led_dev_no,0,1,"leddev");
}
if(result < 0)
{
printk(KERN_WARNING"led: can't get major %d\n",led_major);
return result;
}
cdev_init(&led_cdev, &leddev_fops);
led_cdev.owner = THIS_MODULE;
result = cdev_add(&led_cdev,led_dev_no,1);
if(result < 0)
{
printk(KERN_WARNING"led: can'cdev_add ");
goto fail_alloc_chrdev_region;
}
dev_class = class_create(THIS_MODULE,"leddev");
if(IS_ERR(dev_class))
{
printk("class_create failed\n");
result = PTR_ERR(dev_class);
goto fail_class_create;
}
dev_device = device_create(dev_class,NULL,led_dev_no,NULL,"leddev");
if(IS_ERR(dev_device))
{
printk("class_create failed\n");
result = PTR_ERR(dev_device);
goto fail_device_create;
}
return 0;
fail_device_create:
class_destroy(dev_class);
fail_class_create:
cdev_del(&led_cdev);
fail_alloc_chrdev_region:
unregister_chrdev_region(led_dev_no,1);
return result;
}
static void __exit leddev_exit(void)
{
device_destroy(dev_class,led_dev_no);
class_destroy(dev_class);
unregister_chrdev_region(led_dev_no,1);
cdev_del(&led_cdev);
return ;
}
module_init(leddev_init);
module_exit(leddev_exit);
MODULE_LICENSE("GPL");
dev_device = device_create(dev_class,NULL,led_dev_no,NULL,"leddev"); 改为
<pre name="code" class="cpp">dev_device = class_device_create(dev_class,NULL,led_dev_no,NULL,"leddev"); 内核不再崩溃
自动生成设备文件
[root@Tech automkod]# ll /dev/leddev
crw------- 1 root root 252, 0 07-11 01:09 /dev/leddev