安装编译内核所需要的软件(也可不装,除非你要用 make menuconfig,用make oldconfig不要)
$ sudo apt-get install build-essential kernel-package libncurses5-dev fakeroot
下载内核源码
$ sudo apt-get install linux-source-2.6.38 $ls linux-2.6.38.8 linux-headers-2.6.38-8 linux-2.6.38.8.tar.bz2 linux-headers-2.6.38-8-generic
现在我们需要/boot目录下的config-2.6.38-8-generic文件,我们把它拷贝到我们刚下好解压的目录,也就是linux-source-2.6.35
$ sudo cp /boot/config-2.6.38-8-generic /usr/src/linux-2.6.38/.config $ cd /usr/src/linux-source-2.6.35
$ sudo make menuconfig
终端会弹出一个配置界面
![](http://hi.csdn.net/attachment/201108/20/0_1313840563rEpB.gif)
最后有两项:
load a Alternative kernel configuration...
save a Alternative configuration...
选择load a kernel configuration保存,然后在选择save akernel configuration再保存退出,并退出配置环境。
接下来我们就要开始编译了。
$ cd /usr/src/linux-2.6.38-8 $ make 这个过程很久。耐心等待
$ make bzImage 执行结束后,可以看到在当前目录下生成了一个新的文件: vmlinux。
$ make modules $ make modules_install
在工作空间的任意一个目录下:
$ vi 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 "exit hello\n"); } module_init(hello_init); module_exit(hello_exit);
# vi Makefileobj-m := hello.o KERNELDIR := /lib/modules/2.6.38-8-generic/build PWD := $(shell pwd) modules: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules modules_install: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install clean: rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions $(TARGET) (记住$(MAKE))那里有个TAB一下,否则回出错。
把hello.ko加载到内核
$insmod ./hello.ko
查看hello
$ lsmod|grep hello hello 12448 0 把hello这个模块移除掉
$rmmod hello 查看 hello的输出
$ cat /var/log/syslog Aug 21 03:23:59 lab kernel: [10427.838397] hello,world Aug 21 03:26:53 lab kernel: [10601.623061] exit hello