Linux - 编写第一个内核模块

创建"test"目录并添加源码文件

Terminal Command
$ mkdir test
$ cd test
$ touch Makefile
$ touch test.c
// Makefile
// 注意缩进使用TAB
ifneq ($(KERNELRELEASE),)
    obj-m := test.o
else
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
endif

// test.c
#include <linux/module.h>
#include <linux/kernel.h>

static int __init test_init(void)
{
        printk(">>> test_init\n");
        return 0;
}

static void __exit test_cleanup(void)
{
        printk(">>> test_cleanup\n");
}

module_init(test_init);
module_exit(test_cleanup);

MODULE_LICENSE("GPL");



编译测试

Terminal Command
$ make
$ sudo insmod test.ko
$ sudo rmmod test.ko

使用dmesg可以查看模块打印的内核日志

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。