It's the same as the code first.
Demo.c
#include <linux/init.h>#include<linux/module.h>#include<linux/kernel.h>#include<linux/cdev.h>#include<linux/fs.h>intDemo_major = -;intDemo_minor =0;intDemo_count =1;structCdev Cdev;intDemo_open (structInode *INODEP,structFile * Filep)//turn on the device{PRINTK ("%s,%d\n", __func__, __line__); return 0;}intDemo_release (structInode * INODEP,structFile * Filep)//turn off the device{PRINTK ("%s,%d\n", __func__, __line__); return 0;}structFile_operations FoPs ={. Owner=this_module,. Open=Demo_open,. Release=Demo_release,};Static int__init Demo_init (void){ intRET =0; dev_t Devno; PRINTK ("%s,%d\n", __func__, __line__); //Use the following macros to generate dev_t with the main device number and the secondary device numberDevno =MKDEV (Demo_major, Demo_minor); PRINTK ("devno:%d\n", Devno); PRINTK ("demo_major:%d\n", Demo_major); /** before calling the Cdev_add () function to register a character device with the system, you should first call the Register_chrdev_region () or alloc_chrdev_region () function to request a device number from the system **/ if(demo_major) {ret= Register_chrdev_region (Devno,1,"Demo"); } Else{ret= Alloc_chrdev_region (&devno,0,1,"Demo"); } if(ret) {PRINTK ("Failed to register_chrdev_region.\n"); returnret; } //The cdev_init () function initializes the members of the Cdev and establishes a connection between Cdev and File_operationsCdev_init (&cdev, &fops); Cdev.owner=This_module; //the system adds a cdev to complete the registration of the character device. ret = Cdev_add (&Cdev, Devno, Demo_count); if(ret) {PRINTK (Kern_notice"Failed to Cdev_add [Error]%d adding demo%d", ret, demo_count); Unregister_chrdev_region (Devno, Demo_count); returnret; } return 0;}Static void__exit Demo_exit (void) {PRINTK ("%s,%d\n", __func__, __line__); //Delete a cdev to complete the logoff of the character device. Cdev_del (&Cdev); //after calling the Cdev_del () function to unregister the character device from the system, unregister_chrdev_region () should be called to release the previously requested device number.unregister_chrdev_region (MKDEV (Demo_major, Demo_minor), demo_count);} Module_init (Demo_init); Module_exit (Demo_exit); Module_author ("libra13179"); Module_license ("GPL v2");
Makefile
VERS = $ (Shell uname-R) # Kernel Modulesobj-M + = for the module compilation. #EXTRA_CFLAGS /c3>=-g-o0build:kernel_moduleskernel_modules: -c/lib/modules/$ (kvers)/build m=$ (CURDIR) Modulesclean: -c/lib/modules/$ (kvers)/build m=$ (CURDIR) Clean
Make Test
Use the DMESG directive to view
Use Cat/proc/devices to see demo information
Now mainly introduces the use of DEMO.C in functions and macros, structs, etc.
Linux Driver Development (iii) character device driver framework