阡陌 发表于 2024-2-18 14:43:06

创建一个内核模块实例



源代码:

```c
#include <linux/init.h> //包含模块初始化、清除函数
#include <linux/module.h> //包含许多符号和函数的定义,模块的定义
#include <linux/kernel.h>

static int __init hello_init(void)
{
    printk(KERN_ALERT "Hello World!\n");   //内核中的打印只有printk,而且分打印级别
    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, see you again!\n");
}

module_init(hello_init); //函数声明,把代码段放到init段;module_init是该程序的入口函数
//当系统启动init程序的时候,执行module_init()里的函数
module_exit(hello_exit);
//当系统启动exit程序的时候,执行module_exi()里的函数
//没有module声明的函数(普通函数)会放到代码段(文本段)

MODULE_AUTHOR("Matt <matt@mculoop.com>"); //声明作者
MODULE_DESCRIPTION("Linux Kernel Hello World Module (C) 2018");//模块描述
MODULE_LICENSE("GPL"); //声明LICENSE
```



Makefile:

```makefile
# To build modules outside of the kernel tree, we run "make"
# in the kernel source tree; the Makefile these then includes this
# Makefile once again.
# This conditional selects whether we are being included from the
# kernel Makefile or not.

# called from kernel build system: just declare what our modules are
obj-m := helloworld.o

# Assume the source tree is where the running kernel was built
# You should set KERNELDIR in the environment if it's elsewhere
KERNELDIR ?= /home/matt/test/kernel/linux-3.2.0-psp04.06.00.11

# The current directory is passed to sub-makes as argument
PWD := $(shell pwd)

all: modules

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


clean:
        rm -rf *.o *~ core .depend *.symvers .*.cmd *.ko *.mod.c .tmp_versions $(TARGET)
```



编译:

编译前应当确保已经编译过内核,因为要使用内核的Makefile。

```
make
```


页: [1]
查看完整版本: 创建一个内核模块实例