linux 将模块编译进内核

来源:互联网 发布:客户生日提醒软件 编辑:程序博客网 时间:2024/06/06 03:11

首先cd  /tmp

[root@localhost tmp]#vi hello.c


hello.c

[html] view plaincopy
  1. #include <</span>linux/init.h>   
  2. #include <<span style="margin: 0px; padding: 0px; border:none; color: rgb(153, 51, 0); font-weight: bold; background-color:inherit;">linux/module.h>  
  3. #include <<span style="margin: 0px; padding: 0px; border:none; color: rgb(153, 51, 0); font-weight: bold; background-color:inherit;">linux/moduleparam.h>  
  4.   
  5. static int hello_init(void)  
  6.  
  7.    printk("Helloworld\n");
  8.     return 0;  
  9.  
  10.   
  11. static void hello_exit(void)  
  12.  
  13.     printk("Goodbyeworld\n");
  14.  
  15.   
  16. module_init(hello_init);  
  17. module_exit(hello_exit);  

这个文件需要编译成模块,创建Makefile

 

[root@localhost tmp]# vi Makefile


Makefile

[html] view plaincopy
  1. obj-m   :hello.o  
  2. KERNELDIR :/lib/modules/$(shell uname -r)/build  
  3. PWD       :$(shell pwd)  
  4.   
  5. default:  
  6.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules  
  7.   
  8. clean:  
  9.     rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions  

其中 uname -r是查看内核版本,     我们这里显示的是3.11.10-301.fc20.x86_64
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
-C$(KERNELDIR)
表示在$(KERNELDIR)目录下执行make命令。
-M=$(PWD)
表示包含$(PWD)下的Makefile文件。
modules
表示模块编译

在终端中执行make

[root@localhost tmp]# make

make -C/lib/modules/3.11.10-301.fc20.x86_64/build M=/tmpmodules

make: ***/lib/modules/3.11.10-301.fc20.x86_64/build: No such file ordirectory.  Stop.

 

make: *** [default] Error 2

报错
这是因为一下几个原因:
进入到 /lib/modules/3.11.10-301.fc20.x86_64/  发现build 其实是个链接文件。
首先要确保内核开发包已经安装了,到 /usr/src/kernels/ 下看一看, 有没有类似 3.11.10-301.fc20.x86_64这样的文件夹,  如果没有,就再终端执行 # yum installkernel-devel 
最好后面加个版本号,否则后面insmod的时候会报错
# yuminstall kernel-devel-3.11.10-301.fc20.x86_64
我们这里安装号以后,发现在  /usr/src/kernels/ 下有了3.11.10-301.fc20.x86_64这个文件夹。

然后再重新回到/lib/modules/3.11.10-301.fc20.x86_64文件夹下

[root@localhost3.11.10-301.fc20.x86_64]# ln -s /usr/src/kernels/3.11.10-301.fc20.x86_64/   build
这就把build 和 /usr/src/kernels/3.11.10-301.fc20.x86_64/这个文件夹创建了连接

这时,再重新回到/tmp下。执行make
[root@localhost tmp]# make
make -C /lib/modules/3.11.10-301.fc20.x86_64/build M=/tmpmodules
make[1]: Entering directory`/usr/src/kernels/3.11.10-301.fc20.x86_64'
  CC [M]  /tmp/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC     /tmp/hello.mod.o
  LD [M] /tmp/hello.ko
make[1]: Leaving directory`/usr/src/kernels/3.11.10-301.fc20.x86_64'


此时查看文件夹
[root@localhost tmp]#ls
可以发现生成hello.ko模块

这时候将这个模块加载
[root@localhost tmp]# insmod ./hello.ko

查看所有被加载的内核模块:
[root@localhost tmp]# cat /proc/modules
可以发现刚加载的hello
hello 12496 0 - Live 0xffffffffa03b1000 (POF)


查看记录(-c 是每次查看完缓冲区并清空   这里不加-c 就不清空)
[root@localhost tmp]# dmesg-c
可以发现
[ 8325.905181] Hello world

卸载模块
[root@localhost tmp]# rmmodhello


查看记录
[root@localhost tmp]# dmesg -c
可以发现
[ 8456.036882] Goodbye world


0 0