您的位置:首页 > 其它

LLD3学习笔记(2) hello world

2016-08-28 14:02 120 查看
一 、系统环境
系统:ubuntu5.04内核版本:2.6.10
二 、hello world模块
//hello.c
#include<linux/init.h>
#include<linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
printk(KERN_ALERT"hello,world\n");
return 0;
}

static void hello_exit(void)
{
printk(KERN_ALERT"Goodby , cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);
三、编译和装载
#Makefile
ifneq ($(KERNELRELEASE),)
obj-m:=hello.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

由于刚开始学习,对Makefile不是很了解,不懂里面的原理,后面学会有时间再解释下。
编译完之后加载、卸载。
#insmod hello.ko
#rmmod hello.ko
#dmesg | tail -2

hello,world
Goodby , cruel world
四、使用moduleparam
//hello_param.c
#include<linux/init.h>
#include<linux/module.h>
#include<linux/moduleparam.h>

MODULE_LICENSE("Dual BSD/GPL");

static char *who = "xxxx";
static int num = 10;
module_param(who, charp, S_IRUGO);
module_param(num, int, S_IRUGO);

static int hello_init(void)
{
char i;
for(i=0; i<num; i++)
printk(KERN_ALERT"%d hello,world,%s\n" , i ,who);
return 0;
}

static void hello_exit(void)
{
printk(KERN_ALERT"Goodby , cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);
#Makefile
ifneq ($(KERNELRELEASE),)
obj-m:=hello_parama.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
root@ychx:hello_parama# insmod hello_parama.ko who="yyyyy" num=5
root@ychx:hello_parama# rmmod hello_parama
root@ychx:hello_parama# dmesg | tail -6
[104286.928300] 0 hello,world,yyyyy
[104286.928316] 1 hello,world,yyyyy
[104286.928317] 2 hello,world,yyyyy
[104286.928318] 3 hello,world,yyyyy
[104286.928319] 4 hello,world,yyyyy
[104290.874700] Goodby , cruel world


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LDD3 hello world