The easiest Linux drive HelloWorld

Environment: ubuntu 16.04

HelloWorld module in the kernel runtime plug and play, can also be removed at any time.

1, the kernel source code library constructed

View displays the operating system release number:

uname -r: displays the operating system release number 
uname -a: display system name, node name, operating system release number, kernel version, etc.

Download the corresponding version of the kernel source code:

sudo apt-get install linux-source-4.15.0

 

After the download is completed as follows:

 

Unzip the code:

tar jxvf linux-source-2.6.20.tar.bz2 

 

 Enter linux-source-4.15.0 kernel configuration, select the fastest original configuration

make oldconfig

 

 You need to switch to the root directory execution

 

 De-bzImage compile down

make bzImage

make bzImage时报错scripts/sign-file.c:23:30: fatal error: openssl/opensslv.h: No such file or directory

sudo apt-get install libssl-dev

 Next

make modules

This process is a long time about two hours

The next execution

make modules_install

When executing the will in / lib / modules / see 4.15.0-45-generic compiled module files, use the directory to build this path.

2, write driver code

#include <Linux / init.h> 
#include <Linux / the module.h> 
// tell the kernel, the module has an open source license 
MODULE_LICENSE ( "Dual the BSD / the GPL"); 

static int hello_init (void) 
{ 
    the printk (KERN_EMERG "the Load World hello \ n-"); 
    return 0; 
} 

static void hello_exit (void) 
{ 
    the printk (KERN_EMERG" Rmmove the hello World \ n-"); 
} 

the module_init (hello_init); 
the module_exit (hello_exit);

The code represents: loading the kernel module is executed hello_init, is to call the module is removed hello_exit.

printk kernel print function, because the kernel can not use the C language library code, so I can not use printf.

Write the Makefile

obj-m := hello.o 
KERNELDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd) 
modules:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

And then do make to compile

 

 After the execution results are as follows:

 

What we need is hello.ko file

insmod hello.ko

Load module insmod

rmmod hello.ko

rmmod remove module

 

Visible module prints Load Hello World at load module is removed in print Rmmove Hello World.

 

Guess you like

Origin www.cnblogs.com/achao123456/p/11924668.html