4.5 模組引數
可以用「module_param(引數名,引數型別,引數讀/寫許可權)」為模組定義乙個引數,例如下列**定義了1個整型引數和1個字元指標引數:
static int book_num = 4000;
module_param(book_num, int, s_irugo);
static char *book_name = "linux device driver";
module_param(book_name, charp, s_irugo);
在裝載核心模組時,使用者可以向模組傳遞引數,形式為「insmode(或modprobe)模組名 引數名=引數值」,如果不傳遞,引數將使用模組內定義的預設值。如果模組被內建,就無法insmod了,但是bootloader(u-boot)可以通過在bootargs裡設定「模組名.引數名=值」的形式給該內建的模組傳遞引數。
引數型別可以是byte、short、ushort、int、uint、long、ulong、charp(字元指標)、bool或invbool(布林的反),在模組被編譯時會將module_param中宣告的型別與變數定義的型別進行比較,判斷是否一致。除此之外,模組也可以擁有引數陣列,形式為「module_param_array(陣列名,陣列型別,陣列長,引數讀/寫許可權)」。
模組被載入後,在/sys/module/目錄下將出現以此模組名命名的目錄。當「引數讀/寫許可權」為0時,表示此引數不存在sysfs檔案系統下對應的檔案節點,如果此模組存在「引數讀/寫許可權」不為0的命令列引數,在此模組的目錄下還將出現parameters目錄,其中包含一系列以引數名命名的檔案節點,這些檔案的許可權值就是傳入module_param()的「引數讀/寫許可權」,而檔案的內容為引數的值。執行insmod或modprobe命令時,應使用逗號分隔輸入的陣列元素。
現在定義乙個包含兩個引數的模組,並觀察模組載入時被傳遞引數和不傳遞引數時的輸出。
**清單4.4 帶引數的核心模組,源**檔案:
#include
#include // module.h:17:#include 間接包含標頭檔案
#define driver_author "xz@vi-chip.com.cn"
#define driver_desc "a sample driver"
static int book_num = 4000;
module_param(book_num, int, s_irugo);
static char *book_name = "linux device driver";
module_param(book_name, charp, s_irugo);
static int __init hello_init(void)
static void __exit hello_exit(void)
module_init(hello_init);
module_exit(hello_exit);
module_version("v1.0");
module_license("gpl v2");
module_author(driver_author);
module_description(driver_desc);
module_alias(driver_desc);
makefile:
ifeq ($(kernelrelease),)
kerneldir ?= /lib/modules/$(shell uname -r)/build
pwd := $(shell pwd)
all:
$(make) -c $(kerneldir) m=$(pwd) modules
clean:
$(make) -c /lib/modules/$(shell uname -r)/build m=$(pwd) clean
else
obj-m := hello_world.o
endif
對上述模組執行「insmod hello_world.ko」命令載入,相應輸出都為模組內的預設值,通過檢視「dmesg」日誌檔案可以看到核心的輸出:
[29838.775347] book num:4000
[29838.775350] book name:linux device driver
當使用者執行「sudo insmod hello_world.ko book_num=200 book_name='linux kernel'」命令時,輸出的是使用者傳遞的引數:
[29922.817510] book num:200
[29922.817513] book name:linux kernel
另外,在/sys目錄下,也可以看到hello_world模組的引數:
cd /sys/module/hello_world/parameters/
ubuntu@ubuntu2018:/sys/module/hello_world/parameters$ tree -a
.├── book_name
└── book_num
0 directories, 2 files
可以通過「cat book_name」和「cat book_num」檢視它們的值。
第四章 Linux核心模組
注 內容大多摘自 linux裝置驅動開發詳解 第2版 1.特點 2.模組程式結構 1 模組載入函式 一般需要 2 模組解除安裝函式 一般需要 3 模組許可證宣告 必須 4 模組引數 可選 5 模組匯出符號 可選 6 模組作者等資訊宣告 可選 3.模組的載入,解除安裝,檢視 4.printk函式 核心...
第四章 Linux核心模組
4.1 linux核心模組簡介 核心模組特點 1 模組本身不被編譯進核心映像中,從而控制核心的大小。2 模組被載入後,它跟核心中的其他部分完全一樣。核心載入命令 lsmod 核心解除安裝命令 rmmod 加強型核心載入函式 modprobe 優點 載入模組所以來的模組。模組之間的依賴關係可以在 li...
第四章Linux核心模組之二(核心模組程式結構)
4.2 linux核心模組程式結構 乙個linux核心模組主要由如下幾個部分組成。1 模組載入函式 當通過insmod或modprobe命令載入核心模組時,模組的載入函式會自動被核心執行,完成本模組的相關初始化工作。2 模組解除安裝函式 當通過rmmod命令解除安裝某模組時,模組的解除安裝函式會自動...