大概思路:
先在驱动初始化的代码里调用class_create(...)为该设备创建一个class
再为每个设备调用device_create(...)( 在2.6较早的内核中用class_device_create)创建对应的设备
驱动退出函数时先删除设备,再删除类
下面以一个简单字符设备驱动来展示如何使用这几个函数
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
int HELLO_MAJOR = 210;
int HELLO_MINOR = 0;
int NUMBER_OF_DEVICES = 2;
struct class *my_class;
struct cdev cdev;
dev_t devno;
struct file_operations hello_fops = {
.owner = THIS_MODULE
};
static int __init hello_init (void)
{
int result;
devno = MKDEV(HELLO_MAJOR, HELLO_MINOR);
if (HELLO_MAJOR)
result = register_chrdev_region(devno, 2, "memdev");
else
{
result = alloc_chrdev_region(&devno, 0, 2, "memdev");
HELLO_MAJOR = MAJOR(devno);
}
printk("MAJOR IS %d\n",HELLO_MAJOR);
my_class = class_create(THIS_MODULE,"hello_char_class"); //类名为hello_char_class
if(IS_ERR(my_class))
{
printk("Err: failed in creating class.\n");
return -1;
}
device_create(my_class,NULL,devno,NULL,"memdev"); //设备名为memdev
if (result<0)
{
printk (KERN_WARNING "hello: can't get major number %d\n", HELLO_MAJOR);
return result;
}
cdev_init(&cdev, &hello_fops);
cdev.owner = THIS_MODULE;
cdev_add(&cdev, devno, NUMBER_OF_DEVICES);
printk (KERN_INFO "Character driver Registered\n");
return 0;
}
static void __exit hello_exit (void)
{
cdev_del (&cdev);
device_destroy(my_class, devno); //delete device node under 必须先删除设备,再删除class类
class_destroy(my_class); //delete class created by us
unregister_chrdev_region (devno,NUMBER_OF_DEVICES);
printk (KERN_INFO "char driver cleaned up\n");
}
module_init (hello_init);
module_exit (hello_exit);
MODULE_LICENSE ("GPL");