本文主要是介绍hello ko,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、查看内核版本
uname -r
编译内核模块必须有对应的内核版本的源码,不同的机器内核源码位置不同,本实验源码位置如下:
二、编码
//内核模块必须引入的头文件
#include <linux/kernel.h>
#include <linux/module.h>
//内核模块初始化函数,必须以__init作为标志
static int __init hello_init(void)
{printk("hello world");return 0;
}
//内核退出模块
static void __exit hello_exit(void)
{return;
}module_init(hello_init);
module_exit(hello_exit);
//遵守的协议
MODULE_LICENSE("GPL");
三、编写Makefile
obj-m += demo.o #指定编译模块名称,会自动寻找hello.c
CURRENT_PATH:=$(shell pwd)
LINUX_KERNEL:=$(shell uname -r) LINUX_KERNEL_PATH:=/usr/src/kernels/3.10.0-1062.9.1.el7.x86_64/ #内核源码目录 all: make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules #C进入内核目录读取Makefile,M表明后回到当前目录读取Makefile clean: make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean #table不是空格
四、编译内核模块
五、安装内核模块
查看内核模块信息
[root@VM_0_11_centos Oops]# modinfo demo.ko
filename: /home/Oops/demo.ko
license: GPL
retpoline: Y
rhelversion: 7.7
srcversion: FA212459DF3D7FE0878E9BD
depends:
vermagic: 3.10.0-1062.9.1.el7.x86_64 SMP mod_unload modversions
[root@VM_0_11_centos Oops]# insmod demo.ko
[root@VM_0_11_centos Oops]# dmesg | grep hello
[84145.145935] hello world
[84267.629481] hello world
这篇关于hello ko的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!