Linux driver development details

  
                  

The first kernel module (Hello World module)

The code is as follows: View Code #include<linux/init.h> #include<linux/module.h> MODULE_LICENSE("Dual BSD/GPL" ;); static __init int hello_init(void) { //printk function is defined in the kernel for the module, the kernel needs its own print stats //because it runs on its own, and there is no corresponding library function. //The module can call printk because the insmod is loaded, the module is linked to the kernel //the public symbol of the callable kernel, KERN_ALERT is the priority of the message printk(KERN_ALERT"HELLO WORLD\ "); return 0; Static __exit void hello_exit(void) { printk(KERN_ALERT"GoodBye\ "); } module_init(hello_init); module_exit(hello_exit);

Two functions are defined in this module, one is loaded in the module The kernel calls (hello_init) and the other calls (hello_exit) when the module is removed from the kernel; in the above code, module_init and module_exit are two kernel macro definitions that tell the kernel where to start and where to exit, MODULE_LICENSE The macro is used to declare that the module is compliant with a free license, otherwise a warning will appear when the kernel loads. Ok, now you can test the above program accordingly. You must write the corresponding Makefile before testing. The compilation of the module is different from the compilation of the normal program.

Makefile

The code is as follows: View Code #makefile for hello world # KERNELRELEASE is the first variable defined in the kernel source code ifneq ($(KERNELRELEASE),) #determine whether the variable is empty (not defined during the first execution) #未定义Execute the else statement obj-m := HelloWorld.o# indicates that there is a module to be created from the directory file HelloWorld.o. After it is created, name it #HelloWorld.ko #If there is a module named module.ko, come from two The source file, assuming file1.c and file2.c # should be such that obj-m := module.o # module-objs:=file1.o file2.o else KDIR:=/lib/modules/$(shell uname - r)/build all: #When the target of make is all, -C $(KDIR) jumps to the kernel source directory and reads Makefile #M=$(PWD) to return to the current directory to continue reading, execute the current Makefile, When executed again #$(KERNELRELEASE) has been defined, make will read before else Make -C $(KDIR) M=$(PWD) modules clean: rm -rf *.ko *.o *.mod.o *.mod.c *.symvers endif

The corresponding explanation is as above  Open as compiled kernel: must be superuser Enter the make in the current path Compile, enter insmd HelloWorld.ko to load the kernel, use dmesg

Copyright © Windows knowledge All Rights Reserved