Linux 最簡單內核模塊 Hello World 示例

注:如果想要按照本篇實踐,需要有能運行的arm開發板和對應版本的內核(如果想在Linux主機上編譯運行,請參考文末附1

1. 在相應版本內核的driver目錄下新建如下文件:

module file tree

其中文件代碼如下:
/* hello.c */

#include <linux/init.h>#include <linux/module.h>static int hello_init(void)
{
    printk(KERN_INFO "[init] Can you feel me?\n");    return 0;
}static void hello_exit(void)
{
    printk(KERN_INFO "[exit] Yes.\n");
}


module_init(hello_init);
module_exit(hello_exit);

MODULE_AUTHOR("Alan Wang <[email protected]>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("A simple Hello World Module");
MODULE_ALIAS("A simple module");

/* Kconfig */

# drivers/alan_test/Kconfigmenu "ALAN_TEST Driver "comment "ALAN_TEST Driver comment"config ALAN_TEST    bool "ALAN_TEST support"config HELLO
    tristate "hello module test"
    depends on ALAN_TEST

endmenu

/* Makefile */

# drivers/alan_test/Makefile# makefile for the ALAN_TESTobj-$(CONFIG_HELLO)    += hello.o

2. 修改上一級目錄的 Kconfig Makefie:

drivers 下的 Kconfig 末尾 endmenu 前添加一行

source "drivers/alan_test/Kconfig"endmenu

drivers 下的 Makefile 末尾加一行

obj-$(CONFIG_ALAN_TEST)        += alan_test/

3. make menuconfig 添加剛寫好的模塊到內核:

依次是:Device Drivers —->
     ALAN_TEST Driver —->
       *** ALAN_TEST Driver comment ***
       [*] ALAN_TEST support
       < M > hello module test

退出保存 menuconfig

4. 編譯內核:

使用 make 編譯
生成的 zImage (arch/arm/boot/zImage) 燒寫到開發板對應位置。
生成的 hello.ko(drivers/alan_test/hello.ko) 複製到開發板Linux系統的一個目錄下。

5. 插入內核模塊:

insmod

6. 使用 modinfo 查看模塊信息:

modinfomodinfo

附1:編譯模塊在PC上運行

把 hello.c 和 Makefile 放在同一目錄
/* Makefile */

KERNEL_VER = $(shell uname -r)# kernel modulesobj-m += hello.o# specify flags for the module compilationEXTRA_CFLAGS = -g -O0

build: kernel_moduleskernel_modules:
    make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) modulesclean:
    make -C /lib/modules/$(KERNEL_VER)/build M=$(CURDIR) clean

編譯運行步驟如下圖:
hello模塊在PC上編譯運行


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章