主题:《Linux内核模块编程指南》(七)

来源:互联网 发布:ios商城购物app源码 编辑:程序博客网 时间:2024/04/28 04:52

主题:《Linux内核模块编程指南》(七)发信人: kevintz()
整理人: kevintz(2000-06-24 00:41:53), 站内信件《Linux内核模块编程指南》
《Linux Kernel Module Programming Guide》
作者:Ori Pomerantz 中译者:谭志(lkmpg@21cn.com)
  
译者注:
1、LKMPG是一本免费的书,英文版的发行和修改遵从GPL version 2的许可。为了
节省时间,我只翻译了其中的大部分的大意,或者说这只是我学习中的一些中文
笔记吧,不能算是严格上的翻译,但我认为这已经足够了。本文也允许免费发布
,但发布前请和我联系,但不要把本文用于商业目的。鉴于本人的水平,文章中
难免有错误,请大家不吝指正。
2、本文中的例子在Linux(kernel version 2.2.10)上调试通过。你用的Linux必
须支持内核模块的加载,如果不支持,请在编译内核时选上内核模块的支持或升
级你的内核到一个支持内核模块的版本。
   

      
                         第七章  启动参数


    在之前的许多例子,我们必须在内核模块里硬性规定一些东西,例如生成/p
roc文件的文件名或主设备号等。这违背了Unix和Linux的哲学--写灵活的程序,
方便用户定制。

    在程序或内核模块运作之前取得所需的参数是通过命令行参数。内核模块在
这种情况下,我们不会取得argc和argv,而是更好的方法。我们可以在内核模块
里定义全局变量,insmod命令将会为我们填写参数。

    在本章的例子,我们定义了两个参数:str1和str2。我们要做的只是编译内
核模块并用insmod str1=xxx str2=yyy命令运行。init_module被调用的时候,s
tr1和str2将分别指向"xxx"和"yyy"。

    警告:参数是没有类型检查的。如果xxx和yyy是数字,内核将用数字填充st
r1和str2,而不是字符串"xxx"和"yyy"。实际应用中你要自己检查。
(kevintz注:这似乎可以用MODULE_PARM来处理)

/* param.c 
 * 
 * Receive command line parameters at module installation
 */

/* Copyright (C) 1998-99 by Ori Pomerantz */

/* The necessary header files */

/* Standard in kernel modules */
#include <linux/kernel.h>   /* We're doing kernel work */
#include <linux/module.h>   /* Specifically, a module */

/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#endif        


#include <stdio.h>  /* I need NULL */


/* In 2.2.3 /usr/include/linux/version.h includes a 
 * macro for this, but 2.0.35 doesn't - so I add it 
 * here if necessary. */
#ifndef KERNEL_VERSION
#define KERNEL_VERSION(a,b,c) ((a)*65536+(b)*256+(c))
#endif



/* Emmanuel Papirakis:
 *
 * Prameter names are now (2.2) handled in a macro.
 * The kernel doesn't resolve the symbol names
 * like it seems to have once did.
 *
 * To pass parameters to a module, you have to use a macro
 * defined in include/linux/modules.h (line 176).
 * The macro takes two parameters. The parameter's name and
 * it's type. The type is a letter in double quotes.
 * For example, "i" should be an integer and "s" should
 * be a string.
 */


char *str1, *str2;


#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
MODULE_PARM(str1, "s");
MODULE_PARM(str2, "s");
#endif


/* Initialize the module - show the parameters */
int init_module()
{
  if (str1 == NULL || str2 == NULL) {
    printk("Next time, do insmod param str1=<something>");
    printk("str2=<something>/n");
  } else
    printk("Strings:%s and %s/n", str1, str2);

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
  printk("If you try to insmod this module twice,");
  printk("(without rmmod'ing/n");
  printk("it first), you might get the wrong"); 
  printk("error message:/n");
  printk("'symbol for parameters str1 not found'./n");
#endif

  return 0;
}


/* Cleanup */
void cleanup_module()
{
}  

本章的例子很简单,相信大家自己都可以搞定:-)
原创粉丝点击