学习《linux内核模块编程指南》第2章节 hello world 内核模块
1. 当在init_module初始化函数中,返回非0,函数初始化失败,模块加载失败
如:
- static int hello_init(void)
-
{
-
printk(KERN_ALERT "hello, world\n");
-
return 0;
-
}
加载模块后显示如下:
- ywx@ywx:~/Desktop/module/hello$ dmesg | tail -3
-
[ 3626.517217] hello, world
-
[ 3626.517633] print_hello
-
[ 3630.949706] bye, world
如果,我将hello_init返回值,修改为非0,那么在编译成模块后,不能正常加载模块,错误如下显示
- static int hello_init(void)
-
{
-
printk(KERN_ALERT "hello, world\n");
-
return 1;
-
}
- ywx@ywx:~/Desktop/module/hello$ dmesg | tail -8
-
[ 3670.816134] sys_init_module: 'hello'->init suspiciously returned 1, it should follow 0/-E convention 加载失败
-
[ 3670.816136] sys_init_module: loading module anyway...
-
[ 3670.816253] Pid: 3372, comm: insmod Not tainted 2.6.35-31-generic #63-Ubuntu
-
[ 3670.816307] Call Trace:
-
[ 3670.816885] [<c05c95a1>] ? printk+0x2d/0x34
-
[ 3670.817047] [<c0181905>] sys_init_module+0x1d5/0x1e0
-
[ 3670.817078] [<c05cc204>] syscall_call+0x7/0xb
-
[ 3680.924736] bye, world
=============
2.4章节 __init __exit __initdata 宏
宏__initdata同__init类似,只不过对变量有效
- static int hello_data __initdata = 3;
-
static int hello_init(void)
-
{
-
printk(KERN_ALERT "hello, world hello_data=%d\n",hello_data);
-
return 0;
-
}
========
2.6从命令行传递参数给内核模块
- #include <linux/init.h>//__init __exit __initdata
-
#include <linux/module.h>//MODULE_LICENSE
-
#include <linux/kernel.h>//printk
-
#include <linux/moduleparam.h>//module_param
-
#include <linux/stat.h>//S_IRUGSR
-
-
static int hello_data __initdata = 3;
-
-
static int howmany = 1;
-
static char *whom = "apologize";
-
-
module_param(howmany,int,00444);//S_IRUGO=00444
-
module_param(whom,charp,S_IRUGO);//char point
-
//bool,invbool,charp,int,long,short,uint ulong ushort
-
//module_param(name,type,num,perm);
-
-
static int hello_init(void)
-
{
-
printk(KERN_ALERT "hello, world hello_data=%d\n",hello_data);
-
printk("howmany=%d\n",howmany);
-
printk("whom=%s\n",whom);
-
return 0;
-
}
显示如下:
- ywx@ywx:~/Desktop/module/hello$ sudo insmod ./hello.ko howmany=123 whom="jj"
-
ywx@ywx:~/Desktop/module/hello$ sudo rmmod hello
-
ywx@ywx:~/Desktop/module/hello$ dmesg | tail - 4
-
[ 8375.884555] hello, world hello_data=3
-
[ 8375.884581] howmany=123
-
[ 8375.884597] whom=jj
-
[ 8385.706078] bye, world
阅读(1538) | 评论(0) | 转发(0) |