内核开发的第一个例子

来源:互联网 发布:淘宝卖家修改所在地 编辑:程序博客网 时间:2024/06/05 00:56

前提是:

配置好了内核源码树。

代码如下:(可放到任何位置)

maokx@localhost learn]$ more 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");//printk在Linux内核中定义,功能和标准C库的函数printf类似。
 return 0;
 }

static void hello_exit(void)
 {
  printk(KERN_ALERT "Goodby,cruel world \n");
 }

module_init(hello_init);//一个模块装载到内核时调用
module_exit(hello_exit);//一个模块被移除内核时调用


编译文件如下: 

[root@localhost first]# more Makefile
 obj-m := hello.o #说明有一个模块需要从目标文件hello.o中构造,而从该目标文件中构造的模块名称为hello.ko
 all:
  # -C首先改变目录到指定位置(即内核源代码目录),其中包存有内核的顶层 makefile文件;
  #M=选项让该makefile在构造modules目标之前返回到模块源代码目录,然后,modules目标指向obj-m变量中设定的模块。
   make -C /usr/src/linux M=`pwd` modules
   
编译结果:
[root@localhost first]# make
make -C /usr/src/linux M=`pwd` modules
make[1]: Entering directory `/usr/src/linux-2.6.32.63'
  CC [M]  /home/maokx/learn/first/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/maokx/learn/first/hello.mod.o
  LD [M]  /home/maokx/learn/first/hello.ko
make[1]: Leaving directory `/usr/src/linux-2.6.32.63'
[root@localhost first]# ls
hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers

                                                              
运行:
[root@localhost first]# insmod ./hello.ko
[root@localhost first]# rmmod hello

输出(/var/log/messages):
Sep  2 00:22:45 localhost kernel: Hello,world
Sep  2 00:23:07 localhost kernel: Goodby,cruel world


0 0