#include<linux/init.h>
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/kdev_t.h>
#include<linux/cdev.h>
#include<linux/device.h>
#define DEVICE_CLASS_NAME “chrdev_class_name”
#define DEVICE_NODE_NAME “chrdev_node_name”
static int major_num,minor_num;
module_param(major_num,int,S_IRUSR);
module_param(minor_num,int,S_IRUSR);
dev_t dev_num;
struct cdev cdev;
struct class class;
struct device device;
int chrdev_open(struct inodenod,struct filefile)
{
printk(“hello chrdev_open\r\n”);
return 0;
}
struct file_operations chrdev_ops={
.owner = THIS_MODULE,
.open=chrdev_open
};
static int hello_init(void)
{
//printk(“hello\r\n”);
int ret;
if(major_num)
{
dev_num=MKDEV(major_num,minor_num);
ret=register_chrdev_region(dev_num,1,"wlw");
if(ret<0)
{
printk("fail to register\r\n");
return 0;
}
printk("ok to register\r\n");
}
else
{
ret=alloc_chrdev_region(&dev_num,0,1,"wlw1");
if(ret<0)
{
printk("fail to register\r\n");
return 0;
}
printk("alloc to ok\r\n");
major_num=MAJOR(dev_num);
minor_num=MINOR(dev_num);
printk("major=%d\n",major_num);
printk("minor=%d\n",minor_num);
}
cdev.owner=THIS_MODULE;
cdev_init(&cdev,&chrdev_ops);
cdev_add(&cdev,dev_num,1);
class=class_create(THIS_MODULE,DEVICE_CLASS_NAME);
device=device_create(class,NULL,dev_num,NULL,DEVICE_NODE_NAME);
//printk("a=%d\r\n",a);
return 0;
}
static void hello_exit(void)
{
unregister_chrdev_region(MKDEV(major_num,minor_num),1);
cdev_del(&cdev);
device_destroy(class,dev_num);
class_destroy(class);
printk("exit\r\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE(“GPL”);