---
title: "最简单的内核模块例子"
author: "pengcc"
date: "2011-02-20T18:47:45Z"
tags: []
categories: ["操作系统"]
slug: "untitled"
draft: false
lastmod: "2011-02-20T18:47:45Z"
id: 911156
url: "https://pengcc.iteye.com/blog/911156"
---

```
#include <linux/kernel.h> 
#include <linux/module.h> 
#include <linux/init.h> 
static int __init hello_init(void) 
{ 
printk(KERN_INFO "Hello world\n"); 
return 0; 
} 
static void __exit hello_exit(void) 
{ 
printk(KERN_INFO "Goodbye world\n"); 
} 
module_init(hello_init); 
module_exit(hello_exit); 
```

 

•static int \_\_init hello\_init(void)

 

•static void \_\_exit hello\_exit(void)

–Static声明，因为这种函数在特定文件之外没有其它意义

–\_\_init标记, 该函数只在初始化期间使用。模块装载后，将该函数占用的内存空间释放

–\_\_exit标记 该代码仅用于模块卸载。

•Init/exit

–宏：module\_init/module\_exit

–声明模块初始化及清除函数所在的位置

–装载和卸载模块时，内核可以自动找到相应的函数

      module\_init(hello\_init);

      module\_exit(hello\_exit);

 

•Makefile文件

obj-m := hello.o

all:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

clean:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

•Module includes more files

obj-m:=hello.o

hello-objs := a.o b.o

 

•相关命令

–lsmod

–insmod hello.ko

–rmmod hello.ko