内核驱动模块入门

目录
  1. 驱动程序的hello world
  2. 程序及makefile
    1. 加载和卸载驱动

驱动程序的hello world

程序及makefile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#ifndef __KERNEL__
# define __KERNEL__
#endif
#ifndef MODULE
# define MODULE
#endif
// 下面的是主要的内容
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
MODULE_LICENSE("GPL");
static int year=2017;
int hello_init()
{
printk(KERN_WARNING "Hello kernel, it's %d!\n",year);
return 0;
}
void hello_exit()
{
printk("Bye, kernel!\n");
}
// 下面两个为关键的模块函数
module_init(hello_init);
module_exit(hello_exit);

Makefile

obj-m := hello.o

all :
    $(MAKE) -C /usr/src/kernels/2.6.32-642.13.1.el6.x86_64 M=$(PWD) modules

clean:
    $(MAKE) -C /usr/src/kernels/2.6.32-642.13.1.el6.x86_64 M=$(PWD) clean

以上为Centos 64位系统环境;正常情况下也可设置为/lib/modules/$(shell uname -r)/build或/usr/src/kernels/$(shell uname -r)。

执行make编译,可以得到驱动hello.ko

加载和卸载驱动

  • 加载模块: insmod hello.ko

  • 查看模块: lsmod |grep hello

  • 卸载模块: rmmod hello

使用dmesg可以看到内核输出了相应的打印:

Hello kernel, it’s 2017!
Bye, kernel!

说明:
代码说明:
Ubuntu12.10 内核源码外编译 linux模块–编译驱动模块的基本方法
驱动文件的makefile说明可参考:
linux驱动模块Makefile解

本站总访问量