写Linux Kernel Module

转载:  https://wenyuangg.github.io/posts/linux/simple-linux-kernel-module.html

 

1. 先創建一個資料夾 並寫個簡單的 kernel module (hello.c)

mkdir helloworld

cd helloworld

vim hello.c
  • hello.c 的 code 如下:
/* hello.c */
#include <linux/init.h>
#include <linux/module.h>
  
MODULE_DESCRIPTION("Hello_world");
MODULE_LICENSE("GPL");
  
static int hello_init(void)
{
 printk(KERN_INFO "Hello world !\n");
 return 0;
}
  
static void hello_exit(void)
{
 printk(KERN_INFO "ByeBye !\n");
}
  
module_init(hello_init);
/* When u use insmod, it will enter hello_init function */

module_exit(hello_exit);
/* When u use rmmod, it will enter hello_exit function */

 

2. 接著在同個目錄下寫個 Makefile

vim Makefile
  • Makefile 的內容如下:
PWD := $(shell pwd) 
KVERSION := $(shell uname -r)
KERNEL_DIR = /usr/src/linux-headers-$(KVERSION)/
 
MODULE_NAME = hello
obj-m := $(MODULE_NAME).o
 
all: 
 make -C $(KERNEL_DIR) M=$(PWD) modules
clean: 
 make -C $(KERNEL_DIR) M=$(PWD) clean

 

3. 最後就可以使用 sudo make 指令來編譯

將他編譯成 .ko 檔

sudo make

 

4. 使用 insmod 來載入 module

sudo insmod hello.ko

# 載完後用 dmesg 來觀看 kernel 訊息

dmesg

 

可以看到成功 print 出 hello world ! 字串

 

你也可以使用 lsmod 指令來列出目前在使用的 module

# grep "hello" 用來濾出我們的 hello module 

lsmod | grep "hello"

 

 

最後想要移除掉模組的話 要使用 rmmod

sudo rmmod hello.ko

# 再觀察一次 kernel 訊息

dmesg

 

可以看到 print 出了 ByeBye ! 字串

 

 

 

 

转载:https://wenyuangg.github.io/posts/linux/simple-linux-kernel-module.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值