hello_module2.c
static int __init hello_init(void)
{
printk(DEVICE_NAME" Hello world in kernel module\n");
major = register_chrdev(0, DEVICE_NAME, &hello_fops);
if(major < 0){
printk(DEVICE_NAME" register %s fial\n", DEVICE_NAME);
return major;
}
dev_class = class_create(THIS_MODULE, DEVICE_NAME);
if(dev_class == NULL)
printk("device node create fail\n");
else
{
dev_t dev = MKDEV(major, 0);
device_create(dev_class, NULL, MKDEV(major, 0), NULL, "hello");
}
printk(DEVICE_NAME" got major number: %d\n", major);
return 0;
}
hello_module_cdev.c
static int __init hello_init(void)
{
int result;
printk(DEVICE_NAME" Hello world in kernel module\n");
result = alloc_chrdev_region(&g_devno, 0, DEVICE_COUNT, DEVICE_NAME);
if(result < 0)
{
printk("alloc_chrdev_region fail\n");
return result;
}
major = MAJOR(g_devno);
minor = MINOR(g_devno);
cdev_init(&g_cdev, &hello_fops);
g_cdev.ops = &hello_fops;
g_cdev.owner = THIS_MODULE;
result = cdev_add(&g_cdev, g_devno, DEVICE_COUNT);
if(result)
{
printk("add cdev error\n");
unregister_chrdev_region(g_devno, DEVICE_COUNT);
return result;
}
dev_class = class_create(THIS_MODULE, DEVICE_NAME);
if(dev_class == NULL)
{
printk("device node create fail\n");
}
else
{
int i;
for(i = 0; i < DEVICE_COUNT; i++)
device_create(dev_class, NULL, g_devno + i, NULL, "%s%d", DEVICE_NAME, i);
}
printk(DEVICE_NAME" got major number: %d\n", major);
return 0;
}