hello.c
#include <linux/init.h>
#include <linux/module.h>
static int hello_init(void)
{
printk(KERN_ALERT "Hello, world\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("Daul BSD/GPL");
Makefile
obj-m := hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
module:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
rm -rf *.o *.ko .depend *.mod o*.mod .c Module.* modules.*
log
make 编译
hostname:~/Documents$ make
make -C /lib/modules/4.4.0-148-generic/build M=/home/justin/Documents modules
make[1]: Entering directory `/usr/src/linux-headers-4.4.0-148-generic'
CC [M] /home/justin/Documents/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/justin/Documents/hello.mod.o
LD [M] /home/justin/Documents/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-4.4.0-148-generic'
编译后生成其它文件
hostname:~/Documents$ ls
hello.c hello.ko hello.mod.o Makefile modules.order
hello.c~ hello.mod.c hello.o Makefile~ Module.symvers
insmod 安装内核模块
hostname:~/Documents$ sudo insmod hello.ko
[sudo] password for justin:
lsmod 查找模块是否安装成功
hostname:~/Documents$ lsmod | grep hello
hello 16384 0
rmmod 移除模块
hostname:~/Documents$ sudo rmmod hello.ko
查找内核打印函数 prink 输出的log
hostname:~/Documents$ cat /var/log/syslog | grep hello
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776659] hello: loading out-of-tree module taints kernel.
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776661] hello: module license 'Daul BSD/GPL' taints kernel.
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776684] hello: module verification failed: signature and/or required key missing - tainting kernel
hostname:~/Documents$ cat /var/log/syslog | grep Hello
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.778871] Hello, world
Mar 13 17:11:44 justin-virtual-machine kernel: [ 3165.723490] Hello, world
hostname:~/Documents$ cat /var/log/syslog | grep Good
Mar 13 16:54:24 justin-virtual-machine kernel: [ 2125.998689] Goodbye, cruel world
Mar 13 17:12:08 justin-virtual-machine kernel: [ 3190.646031] Goodbye, cruel world