前言 : 驱动程序和一般用户程序不一样,驱动程序作为一个系统模块连接到内核模块来运行,运行在内核空间里面。所以要开发运行自己构造的模块,首先要配置好一个“内核树”,然后把目标模块和内核树连接起来运行。
一.首先获得内核源码
1》查看可以下载的Linux内核源码包:
#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
2》选定要下载的源码包:
#apt-get install linux-source-2.6.32
3》完成后解压
#tar jxvf linux-source-2.6.32.tar.bz2
二.源码获得后开始编译内核
1》进入内核根目录配置好Linux内核:
#make oldconfig
2》编译
#make bzImage
编译时间比较长,完成后在当前目录下生成一个vmlinux.o的文件。
3》编译模块
#make modules
编译时间也比较长
4》安装模块
#make modules_install
完成后会在/lib/modules目录下面生成一个文件夹linux-2.6.32-24-generic,
构造内核树成功!
三.用一个简单的hello模块测试一下
1.编写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);
2.构造makefile文件
ifneq ($(KERNELRELEASE),)
obj-m :=hello.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
makefile写好后直接 #make
生成一个.ko文件 ,hello.ko
3.将模块插入到内核中
#insmod ./hello.ko
模块装载会触发hello.c的init方法,输出hello world 在/var/log/syslog中看一下
4.卸载目标模块
#rmsmod ./hello.ko