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!

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