linux 內核學習----------模塊(LKM:loading kernel module)

可加載內核模塊(LKM)

Linux內核是模塊化組成的,允許內核在運行的時候以模塊的形式動態地添加或刪除代碼。
優點:保證基本內核小,動態增加和刪除

module_init /module_exit

module_init 將模塊的入口函數註冊到系統中
module_exit 將模塊的出口函數註冊到系統中

加載/卸載模塊

  1. 最簡單的加載方法是insmod命令, 一般要以root身份運行命令
    insmod moudle_name.ko
  2. 卸載一個模塊
    rmmod moudle_name

實例—helloworld 模塊

[email protected]:~/test/kernel>more helloworld.c 
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h>

static int helloworld(void)
{
    printk("Hello world!\n");
    return 0;
}

static int __init hello_init(void)
{
    printk("Hello init!\n");
    helloworld();
    return 0;
}

static void __exit hello_exit(void)
{
    printk("Hello exit!\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

gwwu@hz-dev2.aerohive.com:~/test/kernel>more Makefile 
ifneq ($(KERNELRELEASE),)
    obj-m   := helloworld.o
else
    KDIR    := /lib/modules/$(shell uname -r)/build
    PWD             := $(shell pwd)

default:
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

clean:
    rm -rf Module.symvers *.ko *.o *.mod.c .*.cmd .tmp_versions *.ko.unsigned modules.order

endif

編譯運行:

gwwu@hz-dev2.aerohive.com:~/test/kernel>make 
make -C /lib/modules/2.6.32-279.el6.x86_64/build SUBDIRS=/home/gwwu/test/kernel modules
make[1]: Entering directory `/usr/src/kernels/2.6.32-279.el6.x86_64'
  CC [M]  /home/gwwu/test/kernel/helloworld.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/gwwu/test/kernel/helloworld.mod.o
  LD [M]  /home/gwwu/test/kernel/helloworld.ko.unsigned
  NO SIGN [M] /home/gwwu/test/kernel/helloworld.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.32-279.el6.x86_64'
gwwu@hz-dev2.aerohive.com:~/test/kernel>sudo insmod helloworld.ko
gwwu@hz-dev2.aerohive.com:~/test/kernel>sudo rmmod helloworld.ko
gwwu@hz-dev2.aerohive.com:~/test/kernel>sudo tail -f /var/log/messages
Jun 30 15:53:27 hz-dev2 xinetd[1508]: START: tftp pid=27499 from=10.155.61.200
Jun 30 16:08:27 hz-dev2 xinetd[1508]: EXIT: tftp status=0 pid=27499 duration=900(sec)
Jun 30 17:04:28 hz-dev2 kernel: Hello init!
Jun 30 17:04:28 hz-dev2 kernel: Hello world!
Jun 30 17:04:40 hz-dev2 kernel: Hello exit!

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