2013年8月25日 星期日

Linux Kernel Module 3 - command line argument

1. 由command line傳入的value會被視為global
2. 使用module_param() macro來加入變數
3. 在runtime時, insmod會填入從command line輸入的value到相應的變數
4. module_param()有3個params,依序為 變數名稱, 變數型態, 權限
    module_param(name, type, permission)
   目前支援的type有 byte, short, ushort, int, uint, long, ulong, charp, bool
5.若要傳入array或string可以使用 module_param_array() or module_param_string()
  array的話在type之後要多一個count , module被載入的時候user所指定的array length會被fill到此變
  數中 , NULL也可以
6. 使用 module_param_desc()則可以對某一變數做描述

/*
 * hello_5.c - Demonstrates command line argument passing to a module.
 */
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/stat.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Irene");

static short int myshort = 1;
static int myint = 420;
static long int mylong = 9999;
static char *mystring ="blah";
static int myintArray[2]= {6,6};
static int arr_argc = 0;

/*
 * module_param(foo, int , 0000)
 * The first param is the parameters name
 * The second param is it's data type
 * The final argument is the permissions bits,
 * for exposing parameters in sysfs (if non-zero) at a later stage.
 */

module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
MODULE_PARM_DESC(myshort, "A short integer");
module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP |S_IROTH);
MODULE_PARM_DESC(myint, "An integer");
module_param(mylong, long, S_IRUSR);
MODULE_PARM_DESC(mylong, "A long integer");
module_param(mystring, charp, 0000);
MODULE_PARM_DESC(mystring, "A character string");

/*
 * module_param_array(name, type, num, perm);
 * The first param is the parameter's (in this case the array's)name
 * The second param is the data type of the elements of the array
 * The third argument is a pointer to the variable that will store the number
 * of the elements of the array initialized by the user at module loading time
 * The fourth argument is the permission bits
 */
module_param_array(myintArray, int, &arr_argc, 0000);
MODULE_PARM_DESC(myintArray, "An array of integers");

static int __init hello_5_init(void)
{
int i;
printk(KERN_INFO "Hello, world 5\n==============\n");
printk(KERN_INFO "myshort is a short integer: %hd\n", myshort);
printk(KERN_INFO "myint is an integer: %d\n", myint);
printk(KERN_INFO "mylong is a long integer: %ld\n", mylong);
printk(KERN_INFO "mystring is a string: %s\n",mystring);
for(i=0; i<(sizeof myintArray / sizeof(int));i++)
{
printk(KERN_INFO "myintArray[%d] = %d\n", i,myintArray[i]);
}
printk(KERN_INFO "got %d arguments for myintArray.\n", arr_argc);
return 0;
}
static void __exit hello_5_exit(void)
{
printk(KERN_INFO "Goodbye, world 5\n");
}

module_init(hello_5_init);
module_exit(hello_5_exit); 


利用 insmod hello_5.ko 看output messages ( 利用 cat /var/log/messages)








或是 insmod hello_5.ko myint=25 mystring="Irene" myintArray=1,2









可以看到指定的變數都改value了!




沒有留言:

張貼留言

全國推廣動物認領養平台串聯貼紙

全國推廣動物認領養平台串聯貼紙