1. 在內核目錄下新建一個目錄如hello_world命令如下:
mkdir hello_world
2. 編寫hello.c文件,源碼如下:
/*
* a simple kernel module: hello
*
* Copyright (C) 2020 xxx (xxxxx)
*
* Licensed under GPLv2 or later
*/
#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init(void)
{
printk(KERN_INFO "hello World enter\n");
return 0;
}
module_init(hello_init);
static void __exit hello_exit(void)
{
printk(KERN_INFO "hello World exit\n");
}
module_exit(hello_exit);
MODULE_AUTHOR("xx xx <xxxxx>");//作者
MODULE_LICENSE("GPS v2");//模塊許可證聲明,一般用GPL v2
MODULE_DESCRIPTION("A simple hello world module");//模塊描述
MODULE_ALIAS("a simplest module"); //別名
3. 編寫Makefile
KVERS = $(shell uname -r)
obj-m += hello.o
build: kernel_modules
kernel_modules:
make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules
clean:
make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean
4. 在hello_world目錄下執行make命令
$ make
make -C /lib/modules/3.10.0Likaige+/build M=/home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world modules
make[1]: Entering directory '/home/LiKaige/kernel/2_linux-3.10'
CC [M] /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.mod.o
LD [M] /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.ko
make[1]: Leaving directory '/home/LiKaige/kernel/2_linux-3.10'
$ ls *.ko
hello.ko
生成hello.ko文件
5. 常用的幾個命令:
insmod hello.ko //加載模塊
rmmod hello.ko //卸載模塊
lsmod | grep hello //查看模塊是否運行及是否被使用
tail /var/log/messages //查看加載或卸載模塊時內核打印的log
modinfo hello.ko //查看內核模塊參數,如author, license, description等
注意:以上幾個命令都要用root權限
eg:
# insmod hello.ko
# lsmod | grep hello
hello 905 0
# rmmod hello.ko
# tail /var/log/messages
May 25 11:40:37 localhost kernel: hello World exit
May 25 11:40:43 localhost kernel: [ 797.016662] hello World enter
May 25 11:40:43 localhost kernel: hello World enter
May 25 11:40:50 localhost journal: No devices in use, exit
May 25 11:40:58 localhost kernel: [ 812.600537] hello World exit
May 25 11:40:58 localhost kernel: hello World exit
May 25 11:41:08 localhost kernel: [ 821.954504] hello World enter
May 25 11:41:08 localhost kernel: hello World enter
May 25 11:41:10 localhost kernel: [ 824.025106] hello World exit
May 25 11:41:10 localhost kernel: hello World exit
對應完整源碼下載鏈接:
https://download.csdn.net/download/sinat_29891353/12456897