linux 内核学习----------模块(LKM:loading kernel module)

来源:互联网 发布:微信淘宝推广怎么做的 编辑:程序博客网 时间:2024/06/09 15:21

可加载内核模块(LKM)

Linux内核是模块化组成的,允许内核在运行的时候以模块的形式动态地添加或删除代码。
优点:保证基本内核小,动态增加和删除

module_init /module_exit

module_init 将模块的入口函数注册到系统中
module_exit 将模块的出口函数注册到系统中

加载/卸载模块

  1. 最简单的加载方法是insmod命令, 一般要以root身份运行命令
    insmod moudle_name.ko
  2. 卸载一个模块
    rmmod moudle_name

实例—helloworld 模块

gwwu@hz-dev2.aerohive.com:~/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.oelse    KDIR    := /lib/modules/$(shell uname -r)/build    PWD             := $(shell pwd)default:    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modulesclean:    rm -rf Module.symvers *.ko *.o *.mod.c .*.cmd .tmp_versions *.ko.unsigned modules.orderendif

编译运行:

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 modulesmake[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.komake[1]: Leaving directory `/usr/src/kernels/2.6.32-279.el6.x86_64'gwwu@hz-dev2.aerohive.com:~/test/kernel>sudo insmod helloworld.kogwwu@hz-dev2.aerohive.com:~/test/kernel>sudo rmmod helloworld.kogwwu@hz-dev2.aerohive.com:~/test/kernel>sudo tail -f /var/log/messagesJun 30 15:53:27 hz-dev2 xinetd[1508]: START: tftp pid=27499 from=10.155.61.200Jun 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!
原创粉丝点击