找回密码
 立即注册
搜索
查看: 965|回复: 0

创建一个内核模块实例

[复制链接]

267

主题

0

回帖

1162

积分

管理员

积分
1162
发表于 2024-2-18 14:43:06 | 显示全部楼层 |阅读模式

源代码:

#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:

# 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

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|棱讯科技 ( 粤ICP备2024228160号-2|粤公网安备44030002003510号 )

GMT+8, 2024-12-4 00:41 , Processed in 0.016208 second(s), 3 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表