先贴代码:
- #include <linux/init.h> /* Needed for the macros */
- #include <linux/kernel.h>
- #include <linux/module.h> /* Needed for all modules */
- #include <linux/fs.h>
- #include <linux/cdev.h>
- #include <linux/device.h>
-
- MODULE_LICENSE("Dual BSD/GPL");
- MODULE_AUTHOR("ttxgz");
-
- int hello_major = 555;
- int hello_minor = 0;
- int number_of_devices = 1;
-
- int memalloc_major = 111;
- int memalloc_minor = 1;
-
- struct cdev cdev;
- dev_t dev = 0;
-
- struct file_operations hello_fops = {
- .owner = THIS_MODULE
- };
-
- struct class *my_class;
- struct class *mem_class;
-
- static int __init hello_init(void)
- {
- int result;
- dev = MKDEV (hello_major, hello_minor);
-
-
- /* 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;
- }
- device_create( my_class, NULL, MKDEV(hello_major, hello_minor), NULL, "hello%d",0);
-
- mem_class = class_create(THIS_MODULE, "mem_class");
- device_create( mem_class, NULL, MKDEV(memalloc_major, memalloc_minor), NULL, "memalloc");
-
- printk(KERN_ALERT "Hello, world!/n");
- return 0;
- }
-
- static void __exit hello_exit(void)
- {
-
- dev_t devno = MKDEV (hello_major, hello_minor);
- device_destroy(my_class, MKDEV(hello_major, 0)); //delete device node under /dev
- class_destroy(my_class); //delete class created by us
- unregister_chrdev_region (devno, number_of_devices);
-
-
- devno = MKDEV(memalloc_major,memalloc_minor);
- device_destroy(mem_class, MKDEV(memalloc_major, memalloc_minor)); //delete device node under /dev
- class_destroy(mem_class); //delete class created by us
-
- printk (KERN_INFO "char driver cleaned up\n");
- printk(KERN_ALERT "Goodbye, cruel world/n");
- }
-
- module_init(hello_init);
- module_exit(hello_exit);
makefile是这样的:
- ifeq ($(KERNELRELEASE),)
-
- # Assume the source tree is where the running kernel was built
- # You should set KERNELDIR in the environment if it''s elsewhere
-
- KERNELDIR ?= /lib/modules/$(shell uname -r)/build
-
- # The current directory is passed to sub-makes as argument
-
- PWD := $(shell pwd)
-
- modules:
- $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
|