iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0
Software Development

十年後重讀作業系統恐龍本系列 第 2

ch2第一部份-產生核心模組

  • 分享至 

  • xImage
  •  

產生核心模組,載入和移除和新模組

simple.c
以下程式描述一個非常基本的的核心模組,此模組在核心模組被載入或卸載時會列印適當的訊息。

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

/* This function is called when the module is loaded. */
int simple_init(void)
{
       printk(KERN_INFO "Loading Module\n");

       return 0;
}

/* This function is called when the module is removed. */
void simple_exit(void) {
	printk(KERN_INFO "Removing Module\n");
}

/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");

simple_init():模組進入點,此函數在被載入核心時會被呼叫。
simple_ecit():模組離開點,此函數從核心移除時會被呼叫。
printk():核心內相當於printf()的函數,但他的輸出送到核心紀錄緩衝區,可用dmesg指令讀出。

Makefile
編譯程式

obj-m += simple.o
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

Terminal
在終端機一行一行輸入

make
sudo insmod simple.ko
sudo dmesg
sudo rmmod simple
sudo dmesg -c

結果:
https://ithelp.ithome.com.tw/upload/images/20240916/20168766nSloY11iLg.png

參考:greggagne/OSC9e/ch2


上一篇
Outline-其實要做的事沒想像中的多嘛
下一篇
ch3圖3.30-Line A 將輸出什麼?
系列文
十年後重讀作業系統恐龍本12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言