Linux驱动模块初始教程:一步一步,从helloworld到insmod

转自:

【0】笔者的配置环境XP->VMWare 7.1->Ubuntu 9.04

【1】有必要查询下Linux内核# uname -r2.6.28-11-generic

# ls /usr/src/linux-headers-2.6.28-11 linux-headers-2.6.28-11-generic

由此可见内核版本和内核头文件版本是一致的,都是2.6.28-11。(如果不一致的话在insmod一步必定出错:Error inserting ‘./hello.ko’: -1 Invalid module format网上有纠正这个错误的方法,但是感觉是在投机——躲避内核的版本检查;笔者在安装Ubuntu 8.04的时候出现过header头文件和内核版本不匹配的问题,,后来通过重装Ubuntu为9.04解决之)。

【2】编写hello.c新建自己的工作目录,如:# mkdir /home/wk/hello

编写hello.c# cd /home/wk/hello# gedit hello.c加入以下内容://Begin—hello.c#include</usr/src/linux-headers-2.6.28-11/include/linux/init.h>#include</usr/src/linux-headers-2.6.28-11/include/linux/module.h>

MODULE_LICENSE("GPL");//printk(KERN_ALERT "Begin\n");static int hello_init(void){printk(KERN_ALERT "Hello World!\n");return 0;}

static void hello_exit(void){printk(KERN_ALERT "Good bye, ubuntu\n");// return 0;}

module_init(hello_init);module_exit(hello_exit);//End—hello.c注意第一行#include</usr/src/linux-headers-2.6.28-11/include/linux/init.h>位置要正确;或者你只要写成#include<linux/init.h>保存退出(Ctrl+Q)。

【3】编写Makefile# cd /home/wk/hello# gedit Makefile注意大小写。#Begin—MakefileKERNELDIR=/lib/modules/2.6.28-11-generic/buildPWD:=$(shell pwd)INSTALLDIR=/home/wk/hello/installobj-m:= hello.omodules:$(MAKE) -C $(KERNELDIR) M=$(PWD) modulesmodules_install:cp hello.ko $(INSTALLDIR)clean:rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions.PHONY: modules modules_install clean#End—Makefile网上有Makefile的详解,就不冗述了。保存退出。

【4】开始make# make输出类似以下消息:make -C /lib/modules/2.6.28-11-generic/build M=/home/wk/hello modulesmake[1]: 正在进入目录 `/usr/src/linux-headers-2.6.28-11-generic’Building modules, stage 2.MODPOST 1 modulesmake[1]:正在离开目录 `/usr/src/linux-headers-2.6.28-11-generic’则编译成功,用# ls查看应该可以看到生成一堆文件,如:hello.c hello.mod.c install Makefile1 Module.symvershello.c~ hello.mod.o Makefile Module.markershello.ko hello.o Makefile~ modules.order

【5】安装模块:# insmod hello.ko或者# insmod ./hello.ko一个意思。这一步完了没反应。接着再试一次:# insmod hello.ko提示错误:insmod: error inserting ‘hello.ko’: -1 File exists说明hello模块是安装成功的。用# lsmod也能查看到hello模块。防止打印太多,用:# lsmod | head -5只显示前5行等。如:Module Size Used byhello 9344 0 binfmt_misc 16776 1 bridge 56340 0 stp 10500 1 bridge看到hello模块了吧~~~可是为什么不打印呢?先不说这个。。。

【6】卸载模块# rmmod hello.ko再用# lsmod | head -5发现hello模块已经不存在了。

【7】关于printk现在谈谈这个问题:insmod的时候,printk问什么没有在终端中显示Hello World呢?因为hello.c中明明是这么写的:static int hello_init(void){printk(KERN_ALERT "Hello World!\n");return 0;}答案只有一句:printk不显示在超级终端上!靠!为什么?我也不知道。。。

【8】printk调试信息打印的补救方法用命令:# dmesg | tail -8这个命令格式类似于lsmod(只显示最后8行)。[ 95.586960] Good bye, ubuntu[ 96.483964] Hello World![ 97.031787] Good bye, ubuntu[ 97.594151] Hello World![ 98.109896] Good bye, ubuntu[ 98.615569] Hello World![ 99.098943] Good bye, ubuntu[ 1893.976170] Hello World!以上的信息显示:笔者在95.586960做了rmmod hello.ko,在96.483964做了insmod hello.ko……这里[]中的数字表示执行模块安装/卸载聚开机的时间,如96.483964 S(约开机一个半小时以后)。

启程了,人的智慧才得以发挥。

Linux驱动模块初始教程:一步一步,从helloworld到insmod

相关文章:

你感兴趣的文章:

标签云: