# Install

# 開發套件

sudo apt install build-essential kernel-package libncurses5-dev libelf-dev gcc g++

# linux-headers

sudo apt install linux-headers-$(uname -r)-generic

# Make Kernel Module

先建立一個資料夾,進入資料夾後創建 Makefile 和 main.c

# Makefile

mname := brook_modules
$(mname)-objs := main.o
obj-m := $(mname).o
KERNELDIR := /lib/modules/`uname -r`/build
all:
	$(MAKE) -C $(KERNELDIR) M=`pwd` modules
clean:
	$(MAKE) -C $(KERNELDIR) M=`pwd` clean

# main.c

#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
static int __init init_modules(void)
{
    printk("hello world\n");
    return 0;
}
static void __exit exit_modules(void)
{
    printk("goodbye\n");
}
module_init(init_modules);
module_exit(exit_modules);

# Compiler

撰寫完畢後進進行編譯

make

# 執行

# 掛載

sudo insmod brook_modules.ko // 系統訊息會列印 hello world

# 卸載

sudo rmmod brook_modules.ko // 系統訊息會列印 goodbye

# 查看系統訊息

demsg

# 參考來源

  • http://limitx5.blogspot.com/2018/11/ubuntu-ubuntu-1804-kernel-module.html
  • http://nano-chicken.blogspot.com/2009/11/linux-modulesi.html