Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 核心模組開發詳解:從載入機制到檔案操作實作

編輯:Linux 教學

Linux 核心模組開發是驅動程式工程師的必修課。本文系統梳理模組載入流程、初始化與清理機制、模組參數傳遞、多檔案編譯、file_operations 結構體兩種寫法等核心知識點,並提供可直接參考的程式碼範本。

一、模組載入流程

  1. modprobe 先查 /etc/modules.conf 別名
  2. 依 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)。

六、多檔案編譯單一模組

  1. 其中一個原始檔加入:
    #define __NO_VERSION__
    #include <linux/module.h>
  2. 各檔案分別編譯
  3. 連結:ld -m elf_i386 -r -o <1st.o> <2nd.o>

七、實用除錯工具

  • strace:追蹤程式系統呼叫

八、file_operations 結構體兩種初始化寫法

傳統寫法:

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 寫法可增強可讀性與維護性。

Copyright © Windows教程網 All Rights Reserved