在VMware里Ubuntu下编译内核 运行一个示例的驱动程序


1.下载并安装所需要的工具:
$ apt-get install kernel-package libncurses5-dev bzip2

2.下载linux-kernel的新源码:

http://www.kernel.org/
下载完整的源码,即F
在这里我下载的是
linux-2.6.29.4.tar.bz2

3.解压源码:
$ tar xvjf linux-2.6.29.4.tar.bz2

4.建立编译配置文件
$ cd linux-2.6.29.4
$ vi Makefile
修改EXTRAVERSION = .4EXTRAVERSION = -4-generic
$ sudo cp /boot/config-2.6.28-11-generic ./.config
$ make menuconfig
配置自己的选项或选择Load an Alternate Configuration File使用系统的配置

5.编译deb安装包
$ make-kpkg clean
$ sudo make-kpkg --initrd kernel_image kernel_headers modules_image
编译结束后,将在前一级目录上生成
linux-headers-2.6.29-4-generic_2.6.29-4-generic-10.00.Custom_i386.deblinux-image-2.6.29-4-generic_2.6.29-4-generic-10.00.Custom_i386.deb

6.安装内核镜,及模块包
$ cd ..
$ sudo dpkg -i linux-image-2.6.29-4-generic_2.6.29-4-generic-10.00.Custom_i386.deb
安装完成后,我们就可以在
/lib/modules目录下多出了2.6.29-4-generic目录
/boot目录下多出了config-2.6.29-4-generic,System.map-2.6.29-4-generic,initrd.img-2.6.29-4-generic,vmlinuz-2.6.29-4-generic这几个文件。
/boot/grub/menu.lst文件中多出了一些内容
title           Ubuntu 9.04, kernel 2.6.29-4-generic
uuid            41713c36-058e-4933-a2b3-81f3df0acb38
kernel          /boot/vmlinuz-2.6.29-4-generic root=UUID=41713c36-058e-4933-a2b3-81f3df0acb38 ro locale=zh_CN quiet splash
initrd          /boot/initrd.img-2.6.29-4-generic
quiet

title           Ubuntu 9.04, kernel 2.6.29-4-generic (recovery mode)
uuid            41713c36-058e-4933-a2b3-81f3df0acb38
kernel          /boot/vmlinuz-2.6.29-4-generic root=UUID=41713c36-058e-4933-a2b3-81f3df0acb38 ro locale=zh_CN  single
initrd          /boot/initrd.img-2.6.29-4-generic

7.安装内核头文件:
$ sudo dpkg -i linux-headers-2.6.29-4-generic_2.6.29-4-generic-10.00.Custom_i386.deb
完成后在
/usr/src目录下多出了linux-headers-2.6.29-4-generic头文件的目录

重启电脑。

运行示例驱动程序

//-----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:

ifneq ($(KERNELRELEASE),)
 obj-m := hello.o

else
 KERNELDIR ?= /usr/src/linux-source-2.6.29.4/
 PWD := $(shell pwd)
default:
 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

运行结果:

相关内容