- 论坛徽章:
- 0
|
- #include <linux/module.h>
- #include <linux/kernel.h>
- #include <linux/init.h>
- #include <linux/fs.h>
- #include <linux/cdev.h>
- #include <linux/device.h>
- MODULE_LICENSE ("GPL");
- int hello_major = 120;
- int hello_minor = 0;
- int number_of_devices = 1;
- struct cdev cdev;
- static dev_t dev;
- struct file_operations hello_fops = {
- .owner = THIS_MODULE
- };
- static void char_reg_setup_cdev (void)
- {
- int error;
- cdev_init (&cdev, &hello_fops);
- cdev.owner = THIS_MODULE;
- cdev.ops = &hello_fops;
- error = cdev_add (&cdev, dev, 1);
- if (error)
- printk (KERN_NOTICE "Error %d adding char_reg_setup_cdev", error);
- }
- struct class *my_class;
- static int __init hello_2_init (void)
- {
- int result;
- dev = MKDEV(hello_minor, hello_minor);
- result = register_chrdev_region (dev, number_of_devices, "hello");
- if (result<0) {
- printk (KERN_WARNING "hello: can't get major number %d\n", hello_major);
- return result;
- }
- char_reg_setup_cdev ();
- /* create your own class under /sysfs */
- my_class = class_create(THIS_MODULE, "my_class");
- if(IS_ERR(my_class))
- {
- printk("Err: failed in creating class.\n");
- return -1;
- }
- /* register your own device in sysfs, and this will cause udev to create corresponding device node */
- device_create( my_class, NULL, dev, "hello%d", 0 );
- printk (KERN_INFO "Registered character driver\n");
- return 0;
- }
- static void __exit hello_2_exit (void)
- {
- cdev_del (&cdev);
- device_destroy(my_class, dev);
- class_destroy(my_class);
- unregister_chrdev_region (dev, number_of_devices);
- printk (KERN_INFO "char driver cleaned up\n");
- }
- module_init (hello_2_init);
- module_exit (hello_2_exit);
复制代码 成功编译后,insmod hello.ko,只提示"killed".
若再次insmod hello.ko则会提示insmod error inserting 'hello.ko ':-1 file exists。运行lsmod |grep hello,显示
hello 2849 1
如果rmmod hello.ko,则提示ERROR: Module hello is in use
内核版本为2.6.38.2
希望本版的前辈帮帮忙,困扰了很久。多谢了 |
|