Ubuntu 10.04建立源码树实现最简单的驱动模块

来源:互联网 发布:欧文总决赛数据统计 编辑:程序博客网 时间:2024/06/03 18:01

在Ubuntu 10.04下安装的过程:

1.安装编译内核所需要的软件

build-essential、autoconf、automake、cvs、subversion
apt-get install build-essential kernel-package libncurses5-dev

libncurses5这个软件包在使用menuconfig配置内核的时候会用到。

2.下载内核源码

使用uname -r 命令查看当前的内核版本号,我的是2.6.32-25-generic,使用apt-cache search linux-source查看软件库的源码包,我查询到的源码包有:
linux-source - Linux kernel source with Ubuntu patches
linux-source-2.6.32 - Linux kernel source for version 2.6.32 with Ubuntu patches

我选择linux-source-2.6.32 - Linux kernel source for version 2.6.32 with Ubuntu patches

sudo apt-get install linux-source-2.6.32

下载好后cd /usr/src 目录下就可以看见linux-source-2.6.32.tar.bz2,然后解压到当前的目录
sudo tar xjvf linux-source-2.6.32.tar.bz2

解压完毕,会生成linux-source-2.6.32目录

3.编译内核源码

在编译之前我们需要 ubuntu原来内核的一个配置文件

这是我/usr/src目录下的文件预览:

drwxr-xr-x  4 root root     4096 2010-09-04 21:31 fglrx-8.723.1
drwxr-xr-x 24 root root     4096 2010-09-04 20:35 linux-headers-2.6.32-25
drwxr-xr-x  7 root root     4096 2010-09-04 20:35 linux-headers-2.6.32-25-generic
drwxr-xr-x 25 root root     4096 2010-09-16 21:39 linux-source-2.6.32
-rw-r--r--  1 root root 65846876 2010-09-01 22:41 linux-source-2.6.32.tar.bz2

现在我们需要linux-headers-2.6.32-25-generic目录下的.config文件,我们把它拷贝到我们刚下好解压的目录,也就是linux-source-2.6.32

sudo cp /usr/src/linux-headers-2.6.32-25-generic/.config /usr/src/linux-2.6.32

接下来切换到root用户
sudo -i

cd /usr/src/linux-2.6.32

make menuconfig

终端会弹出一个配置界面

最后有两项:load a kernel configuration... 
save a kernel configuration... 
选择load a kernel configuration保存,然后在选择save akernel configuration再保存退出,并退出配置环境。

接下来我们开始编译

cd /usr/src/linux-2.6.32
make
记住一定要是管理员帐号运行,这个过程真的很久,如果你的cpu是双核的可以在make后面加个参数,make -j4.

make bzImage 执行结束后,可以看到在当前目录下生成了一个新的文件: vmlinux, 其属性为-rwxr-xr-x。 
make modules /* 编译 模块 */ 

make modules_install  这条命令能在/lib/modules目录下产生一个目录.

4.测试驱动模块

这里就抄个程序测试了,初学者顾不了那么多了。

我在 /home/shana/linux_q/ 目录下创建2个文本文件 hello.c Makefile

//hello.c 
#include <linux/init.h> 
#include <linux/module.h> 
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) 

printk(KERN_ALERT "Hello, world\n"); 
return 0; 
}

static void hello_exit(void) 

printk(KERN_ALERT"Goodbye, cruel world\n"); 
}

module_init(hello_init); 
module_exit(hello_exit);

Makefile 文件

obj-m := hello.o 
KERNELDIR := /lib/modules/2.6.20/build 
PWD := $(shell pwd)

modules: 
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install: 
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

需要注意的是makefile的格式$(MAKE)前面要加个tab.
make 编译,产生如下文件:
hello.c   hello.mod.c  hello.o   modules.order
hello.ko  hello.mod.o  Makefile  Module.symvers

5.加载模块到内核去

sudo insmod ./hello.ko 这个命令把hello.ko加载到内核

sudo rmmod hello 这个命令是把hello这个模块移除掉

lsmod 这个命令可以查看当前所有的驱动模块


程序的输出结果可以在
/var/log/syslog文件中查看

Sep 16 21:50:10 wuyangyu-desktop kernel: [10428.551271] Hello,World
Sep 16 21:55:45 wuyangyu-desktop kernel: [10763.644605] Goodbye,cruel world

这是程序的输出。


0 0