Chinaunix

标题: Linux 2.6.xx 内核模块编程入门 [打印本页]

作者: shinety53    时间: 2008-05-24 09:42
标题: Linux 2.6.xx 内核模块编程入门

               
一. 准备工作
安装kernel 必须的开发库
#sudo apt-get install linux-kernel-devel
安装内核头文件
#sudo apt-get install linux-headers-`uname -r`
当然, gcc /make 等工具天生就是需要的。
二. 编写代码 hello.c
如下:
//------------------hello.c-------------------//
#ifndef __KERNEL__
#define __KERNEL__
#endif
#ifndef MODULE
#define MODULE
#endif
#include
#include
#include
static int hello_init(void)
{
        printk(KERN_ALERT "Hello World!\n");
        return 0;
}
static void hello_exit(void)
{
        printk(KERN_ALERT "Bye World!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("WFJ");
//-------------------end of hello.c-------------------//
三. 编写Makefile 文件,与hello.c 放在同一个目录里
obj-m := hello.o
KERNELBUILD :=/lib/modules/`uname -r`/build
default:
        make -C $(KERNELBUILD) M=$(shell pwd) modules
clean:
        rm -rf *.o *.ko *.mod.c .*.cmd .tmp_versions
(注意makefile里面要求的tab)
四. 编译模块
#sudo make
编译模块
这时,在hello.c 所在文件夹就会有 hello.ko ,这个就是我们需要的内核模块啦,哈哈!
#sudo make clean
清理编译垃圾,hello.ko 也会清理掉,呵呵。
四. 插入模块,让其工作
#sudo insmod ./hello.ko
我们用dmesg 就可以看到 产生的内核信息啦,Hello world!
#sudo rmmod ./hello
再用dmesg 可以看到 Bye world!
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/69984/showart_703823.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2