This article describes how to write and load a Linux kernel module, as well as the problems and workarounds encountered during the experiment. This experiment outputs the message "Hello world!" in the System log file when the module is loaded, and outputs the information "Goodbye world!" in the System file when the module is deleted. Includes the following content:
- Experimental environment
- Source
- Demonstration steps
- Problems and Solutions
- Experimental environment Win8 system, Virutalbox 5.0.14 r105127, Ubuntu 15.10 Desktop
- Source
2.1 hello.c
1 //----HELLOMOD.C----//2#include <linux/module.h>3#include <linux/kernel.h>4#include <linux/init.h>5 6Module_license ("GPL");//get rid of taint message7Module_author ("Kunzhang" );8Module_description ("Hello World Module" );9 Ten Static int__init Lkp_init (void ) One { APRINTK (Kern_notice"Hello, world! from the kernel message space ... \ n" ); - return 0; - } the - Static void__exit Lkp_cleanup (void ) - { -PRINTK (Kern_notice"<1>goodbye, world! Leaving kernel space ... \ n" ); + } - + Module_init (lkp_init); AModule_exit (Lkp_cleanup);
2.2 Makefile
1 Ifneq ($ (kernelrelease),)2Obj-m: =hello.o3 Else4Kdir: =/lib/modules/4.2.0- --generic/Build5 6 All :7 Make-C $ (kdir) m=$ (PWD) modules8 Clean :9 RM-F *.ko *.o *.mod.o *mod.c *.symvers *. OrderTenendif
- Demonstration steps
3.0 preparatory work
Create two files in any directory hello.c and Makefile, the file contents are as shown above.
3.1 Compiling the text file
Open the terminal and switch to HELLO.C and the path where Makefile is located
%> make
After a successful compilation, 5 new files are generated in the current directory: Hello.ko, HELLO.MOD.C, Hello.mod.o,modules.order module.symvers. Where Hello.ko is the binary module file that we need.
3.2 Loading and unloading
%> sudo insmod Hello.ko
%> sudo rmomd Hello.ko
3.3 Viewing experimental results
We use the information output function "PRINTK" can not be output on the screen, but the information is written in the system log file/var/log/syslog.
Feb 8:PNS:3850.565815] Hello, world! From the kernel message space ... Feb 8:notoginseng:3856.246795] Goodbye, world! Leaving kernel space ...
- Problems encountered and how to resolve them
This experiment does not have the strange question, the author in the execution process encountered the mistake can be attributed to "insufficiently careful". The following two points should be noted:
A. Note the kernel version that is already on the Linux machine
6. Note Makefile do not have spelling mistakes
- Reference A. "The Linux®kernel primer:a Top-down approach for x86 and PowerPC architectures", Claudia Salzberg Rodriguez, Gordon Fisch Er, Steven Smolski
B. Linux device driver--helloworld
1th Day, Hello World