在桌面新建文件夹,并在文件夹里面新建hello.c , 内容如下:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
MODULE_LICENSE("GPL");
static int __init hello_init(void)
{
printk("init: %s,line=%d\n", __func__, __LINE__);
msleep(1000);
printk("welcome to my linux kernel.\n" );
return 0;
}
static void __exit hello_exit(void)
{
printk("exit:%s,%d\n", __func__, __LINE__);
}
module_init(hello_init);
module_exit(hello_exit);
另外再新建MakeFile文件,内容如下:
$(warning KERNELRELEASE = $(KERNELRELEASE))
ifeq ($(KERNELRELEASE),)
#内核的源码路径, ?= 条件赋值, uname -r 得到内核的版本号
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
# := 立即赋值, 得到当前的绝对路径
PWD := $(shell pwd)
# -C 切换工作路径, make -c
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions Module* modules*
.PHONY: modules clean
else
# 生成模块
obj-m := hello.o
endif
然后在当前目录右击弹出终端,输入make ,生成hello.ko 文件(Kernel Object) 。
输入insmod hello.ko 安装模块 (install module),这时屏幕上没有显示print的内容,输入 dmesg -c ,就可以显示了。
最后输入rmmod hello , 卸载模块!
来源:CSDN
作者:wabil
链接:https://blog.csdn.net/wabil/article/details/103944813