Chinaunix首页 | 论坛 | 博客
  • 博客访问: 444453
  • 博文数量: 72
  • 博客积分: 3186
  • 博客等级: 中校
  • 技术积分: 1039
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-07 16:53
文章分类

全部博文(72)

文章存档

2012年(1)

2011年(5)

2010年(10)

2009年(56)

我的朋友

分类: LINUX

2010-02-24 14:57:48

hello wrold 模块试验
        参考

步骤:

1. 在任意路径下(最好拥有其权限)新建一目录test,用于存放我们的代码。

2. 在test目录下新建源代码文件hello.c,并敲入代码

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

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);

MODULE_LICENSE("GPL");



3. 在test目录下新建Makefile文件

obj-m := hello.o

KERNELDIR := /lib/modules/2.6.28-11-generic/build

PWD := $(shell pwd)

modules:

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

modules_install:   

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


注:
        我这里KERNELDIR的值为 /lib/modules/2.6.28-11-generic/build

[linux@ test]$ ll /lib/modules/2.6.28-11-generic/build
lrwxrwxrwx 1 root root 40 2009-12-05 08:47 /lib/modules/2.6.28-11-generic/build -> /usr/src/linux-headers-2.6.28-11-generic
可以看到build文件实际上是软链接到/usr/src/linux-headers-2.6.28-11-generic目录
的,该目录下存放的是linux内核头文件,且仍保持内核目录结构。

4. make 编译
在目录下生成数个文件
[linux@ test]$ ls
hello.c   hello.mod.c  hello.o   Module.markers  Module.symvers
hello.ko  hello.mod.o  Makefile  modules.order

其中的hello.ko便是我们用来加载的模块了

5. 加载模块
sudo insmod ./hello.ko

查看信息
[linux@ test]$ dmesg | tail -n 1
[22588.694732] Hello, world!

6. 卸载模块
[linux@ test]$ sudo rmmod hello

[linux@ test]$ dmesg | tail -n 1
[22665.554340] Goodbye, cruel world

小结:注意要保证Makefile文件中引用的头文件路径KERNELDIR变量值正确。
      这里只是将试验的过程记录,至于对上面几行代码的解释,google
阅读(1776) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~