Linux 核心模組開發是驅動程式工程師的必修課。本文系統梳理模組載入流程、初始化與清理機制、模組參數傳遞、多檔案編譯、file_operations 結構體兩種寫法等核心知識點,並提供可直接參考的程式碼範本。
modprobe 先查 /etc/modules.conf 別名lib/modules/version/modules.dep 解析相依模組(由 depmod -a 產生)2.4 核心不強制使用 init_module/cleanup_module,但必須用 module_init()、module_exit() 宣告。
__init:初始化函數執行完釋放記憶體__exit:清理函數執行完釋放記憶體__initdata:用於變數#include <linux/init.h>
static int ntest __initdata = 3;
static int __init test_init(void) { ... }
static void __exit test_exit(void) { ... }
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("範例模組");
MODULE_AUTHOR("作者名");
MODULE_SUPPORTED_DEVICE("裝置名稱");
可用 objdump 查看編譯後的模組資訊段。
static int myint = 9;
static char *mystr = "test";
MODULE_PARM(myint, "i"); // 整數
MODULE_PARM(mystr, "s"); // 字串
支援類型:b(byte)、h(short)、i(int)、l(long)、s(string)。
#define __NO_VERSION__#include <linux/module.h>ld -m elf_i386 -r -o <1st.o> <2nd.o>strace:追蹤程式系統呼叫傳統寫法:
struct file_operations fops = {
read: device_read,
write: device_write,
open: device_open,
release: device_release
};
C99 指定初始化器寫法(推薦):
struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
定義於 linux/fs.h,採用 C99 寫法可增強可讀性與維護性。