Linux Kernel 学习笔记2:模块参数

(本章基于:linux-4.4.0-37)

在用户态下编程可以通过main()来传递命令行参数,而编写一个内核模块则可通过宏module_param()来传递命令行参数.

先来看看这个宏的定义(Linux-4.4.0-37)

#define module_param(name, type, perm)				\
	module_param_named(name, name, type, perm)
name:参数名

type:参数类型,byte, short, ushort, int, uint, long, ulong, charp, bool, invbool

perm:权限S_IRUGO, S_IWUGO


例:hello.c

#include <linux/init.h>
#include <linux/module.h>

static int num = 0;
static char *name = NULL;

module_param(num, int, S_IRUGO);
module_param(name, charp, S_IRUGO);

static __init int hello_init(void)
{
        printk(KERN_WARNING "helloworld init!\n");
        printk(KERN_ALERT "num=%d\nname=%s\n", num, name);
        return 0;
}

static __exit void hello_exit(void)
{
        printk(KERN_WARNING "helloworld exit!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Stone");

可在加载模块时带入参数初始值:

#insmod helloworld.ko name=aaaa  num=43

查看内核参数

可在/sys/module/helloworld/parameters/中看到各参数对应的文件,cat其内容可看到参数具体值。

备注:书上说若参数具有权限S_IWUGO即可修改参数值,但试验后发现加上S_IWUGO后无法通过编译,错误如下,望大神指点:

include/linux/bug.h:33:45: error: negative width in bit-field ‘<anonymous>’
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
                                             ^
include/linux/kernel.h:831:3: note: in expansion of macro ‘BUILD_BUG_ON_ZERO’
   BUILD_BUG_ON_ZERO((perms) & 2) +     \
   ^
include/linux/moduleparam.h:225:6: note: in expansion of macro ‘VERIFY_OCTAL_PERMISSIONS’
      VERIFY_OCTAL_PERMISSIONS(perm), level, flags, { arg } }
      ^
include/linux/moduleparam.h:167:2: note: in expansion of macro ‘__module_param_call’
  __module_param_call(MODULE_PARAM_PREFIX, name, ops, arg, perm, -1, 0)
  ^
include/linux/moduleparam.h:147:2: note: in expansion of macro ‘module_param_cb’
  module_param_cb(name, ¶m_ops_##type, &value, perm);     \
  ^
include/linux/moduleparam.h:126:2: note: in expansion of macro ‘module_param_named’
  module_param_named(name, name, type, perm)
  ^
/root/modules/helloworld/hello.c:10:1: note: in expansion of macro ‘module_param’
 module_param(name, charp, S_IWUGO);
 ^
scripts/Makefile.build:258: recipe for target '/root/modules/helloworld/hello.o' failed

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stone8761

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值