Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4236287
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: LINUX

2011-12-17 09:17:02

学习《linux内核模块编程指南》第2章节 hello world 内核模块


在2.2章节 编译内核模块 hello附件: hello.rar   将rar修改为rar
1. 当在init_module初始化函数中,返回非0,函数初始化失败,模块加载失败
如:
  1. static int hello_init(void)
  2. {
  3.         printk(KERN_ALERT "hello, world\n");
  4.         return 0;
  5. }
加载模块后显示如下:
  1. ywx@ywx:~/Desktop/module/hello$ dmesg | tail -3
  2. [ 3626.517217] hello, world
  3. [ 3626.517633] print_hello
  4. [ 3630.949706] bye, world
如果,我将hello_init返回值,修改为非0,那么在编译成模块后,不能正常加载模块,错误如下显示
  1. static int hello_init(void)
  2. {
  3.         printk(KERN_ALERT "hello, world\n");
  4.         return 1;
  5. }
  1. ywx@ywx:~/Desktop/module/hello$ dmesg | tail -8
  2. [ 3670.816134] sys_init_module: 'hello'->init suspiciously returned 1, it should follow 0/-E convention 加载失败
  3. [ 3670.816136] sys_init_module: loading module anyway...
  4. [ 3670.816253] Pid: 3372, comm: insmod Not tainted 2.6.35-31-generic #63-Ubuntu
  5. [ 3670.816307] Call Trace:
  6. [ 3670.816885] [<c05c95a1>] ? printk+0x2d/0x34
  7. [ 3670.817047] [<c0181905>] sys_init_module+0x1d5/0x1e0
  8. [ 3670.817078] [<c05cc204>] syscall_call+0x7/0xb
  9. [ 3680.924736] bye, world
=============
2.4章节 __init __exit __initdata 宏
宏__initdata同__init类似,只不过对变量有效
  1. static int hello_data __initdata = 3;

  2. static int hello_init(void)
  3. {
  4.         printk(KERN_ALERT "hello, world hello_data=%d\n",hello_data);
  5.         return 0;
  6. }
========
2.6从命令行传递参数给内核模块
附件; hello.rar   将rar修改为tar.bz2
  1. #include <linux/init.h>//__init __exit __initdata
  2. #include <linux/module.h>//MODULE_LICENSE
  3. #include <linux/kernel.h>//printk
  4. #include <linux/moduleparam.h>//module_param
  5. #include <linux/stat.h>//S_IRUGSR

  6. static int hello_data __initdata = 3;
  7.  
  8. static int howmany = 1;
  9. static char *whom = "apologize";

  10. module_param(howmany,int,00444);//S_IRUGO=00444
  11. module_param(whom,charp,S_IRUGO);//char point
  12. //bool,invbool,charp,int,long,short,uint ulong ushort
  13. //module_param(name,type,num,perm);

  14. static int hello_init(void)
  15. {
  16.         printk(KERN_ALERT "hello, world hello_data=%d\n",hello_data);
  17.         printk("howmany=%d\n",howmany);
  18.         printk("whom=%s\n",whom);
  19.         return 0;
  20. }
显示如下:
  1. ywx@ywx:~/Desktop/module/hello$ sudo insmod ./hello.ko howmany=123 whom="jj"
  2. ywx@ywx:~/Desktop/module/hello$ sudo rmmod hello
  3. ywx@ywx:~/Desktop/module/hello$ dmesg | tail - 4
  4. [ 8375.884555] hello, world hello_data=3
  5. [ 8375.884581] howmany=123
  6. [ 8375.884597] whom=jj
  7. [ 8385.706078] bye, world
































































阅读(1475) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~