如何向模塊傳遞參數,Linux kernel 提供了一個簡單的框架.
1. module_param(name, type, perm);
name 既是用戶看到的參數名,又是模塊內接受參數的變量;
type 表示參數的數據類型,是下列之一:byte, short, ushort, int, uint, long, ulong, charp, bool, invbool;
perm 指定了在sysfs中相應文件的訪問權限。訪問權限與linux文件訪問權限相同的方式管理,如0644,或使用stat.h中的宏如S_IRUGO表示。
0 表示完全關閉在sysfs中相對應的項。
#define S_IRUSR 00400 文件所有者可讀
#define S_IWUSR 00200 文件所有者可寫
#define S_IXUSR 00100 文件所有者可執行
#define S_IRGRP 00040 與文件所有者同組的用戶可讀
#define S_IWGRP 00020
#define S_IXGRP 00010
#define S_IROTH 00004 與文件所有者不同組的用戶可讀
#define S_IWOTH 00002
#define S_IXOTH 00001
這些宏不會聲明變量,因此在使用宏之前,必須聲明變量,典型地用法如下:
static unsigned int int_var = 0;
module_param(int_var, uint, S_IRUGO);
insmod xxxx.ko int_var=x
2.傳遞多個參數可以通過宏 module_param_array(para , type , &n_para , perm) 實現。
其中,para既是外部模塊的參數名又是程序內部的變量名,type是數據類型,perm是sysfs的訪問權限。指針nump指向一個整數,其值表示有多少個參數存放在數組para中。
para:參數數組; 數組的大小才是決定能輸入多少個參數的決定因素.
n_para:參數個數; 這個變量其實無決定性作用;只要para數組大小夠大,在插入模塊的時候,輸入的參數個數會改變n_para的值,最終傳遞數組元素個數存在n_para中.
典型地用法如下:
static int para[MAX_FISH];
static int n_para;
module_param_array(para , int , &n_para , S_IRUGO);
#include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/delay.h> #include <asm/uaccess.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/arch/regs-gpio.h> #include <asm/hardware.h> static char *name = "Ocean"; static int count = 2; static int para[8] = {1,2,3,4}; static int n_para = 1; module_param(count, int, S_IRUGO); module_param(name, charp, S_IRUGO); module_param_array(para , int , &n_para , S_IRUGO); static struct file_operations first_drv_fops={ .owner = THIS_MODULE, .open = first_drv_open, .write = first_drv_write, }; int first_drv_init(void) { printk("init first_drv drv!\n"); int i; for (i = 0; i < count; i++) printk(KERN_ALERT "(%d) Hello, %s !\n", i, name); for (i = 0; i < 8; i++) printk(KERN_ALERT "para[%d] : %d \n", i, para[i]); for(i = 0; i < n_para; i++) printk(KERN_ALERT "para[%d] : %d \n", i, para[i]); return 0; } void first_drv_exit(void) { printk("exit first_drv drv!\n"); } module_init(first_drv_init); module_exit(first_drv_exit); MODULE_AUTHOR("Ocean Byond"); MODULE_DESCRIPTION("my first char driver"); MODULE_LICENSE("GPL");
數組大小為8,但只傳入4個參數,則n_para=4.
數組大小為8,但只傳入8個參數,則n_para=8.
數組大小為8,傳入9個參數,數組不夠大,無法傳入.