1.首先编写hello.c文件

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");//模块许可声明
static int hello_init(void)//模块加载函数
{
        printk(KERN_ALERT "hello,I am a student\n");
        return 0;
}

static void hello_exit(void)//模块卸载函数
{
        printk(KERN_ALERT "goodbye kernel\n");#printk函数
}

module_init(hello_init);//模块注册
module_exit(hello_exit);

MODULE_AUTHOR("a student has a try");//相关信息
MODULE_DESCRIPTION("This is a simple example!\n");
MODULE_ALIAS("A simplest example");

2.编写Makefile文件

obj-m += hello.o
CURRENT_PATH:=$(shell pwd)#generate the path
LINUX_KERNEL:=$(shell uname -r)#current kernel version
LINUX_KERNEL_PATH:=/lib/modules/$(LINUX_KERNEL)/build #absolute path
all:
        make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules #compile object
clean:
        make -C $(LINUX_KERNEL_PATH) M=$(CURRENT+PATH) clean #clean
第一句话指定要被编译的文件

3.make

完成上述两个文件后,在当前目录下运行make命令,就会生成hello.ko文件,即模块目标文件

root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# ls
hello.c   hello.mod.c  hello.o   modules.order
hello.ko  hello.mod.o  Makefile  Module.symvers

4.insmod,rmmod和dmesg

insmod命令可以使我们写的这个模块加入到内核中,但是一般我们要加上sudo。rmmod当然就是卸载这个模块了。我们在加载或卸载模块时都有一些提示语,即我们printk中显示的语句,这时候可以用dmesg命令来查看
运行结果如下:

root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# dmesg 
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# insmod hello.ko 
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# dmesg 
[801809.377967] hello,I am a student
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# rmmod hello.ko 
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/kernel/linux-3.8/lijy# dmesg 
[801809.377967] hello,I am a student
[801825.225934] goodbye kernel
算是对内核的编程有了一个比较直观的了解了,c 文件如何去编写,后期应该还有很多工作要做。

posted on 2022-07-05 18:12  我在全球村  阅读(20)  评论(0编辑  收藏  举报