一个内核模块的helloworld

helloworld.c

#include <linux/kernel.h>
#include <linux/module.h>
static int __init helloworld_init(void)
{
printk("<0>""helloworld!\n");
return 0;
}
static void __exit helloworld_exit(void)
{
printk("<0>""byebye!\n");
}
module_init(helloworld_init);
module_exit(helloworld_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("haoning");

Makefile

ifneq ($(KERNELRELEASE),)

obj-m := helloworld.o
else

PWD := $(shell pwd)
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
rm -rf *.cmd *.o *.mod.c *.ko *.mod.o *.ko.unsigned modules.order Module.symvers
endif



make
[code="java"]
# make
make -C /lib/modules/2.6.32-431.11.2.el6.x86_64/build M=/data/haoning/kernel modules
make[1]: Entering directory `/usr/src/kernels/2.6.32-431.11.2.el6.x86_64'
CC [M] /data/haoning/kernel/helloworld.o
Building modules, stage 2.
MODPOST 1 modules
CC /data/haoning/kernel/helloworld.mod.o
LD [M] /data/haoning/kernel/helloworld.ko.unsigned
NO SIGN [M] /data/haoning/kernel/helloworld.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.32-431.11.2.el6.x86_64'
#
[/code]

[code="java"]
# ls
helloworld.c helloworld.ko helloworld.ko.unsigned helloworld.mod.c helloworld.mod.o helloworld.o Makefile modules.order Module.symvers
#

# insmod helloworld.ko
#
Message from syslogd@mytest at Jun 4 19:30:47 ...
kernel:helloworld!

# rmmod helloworld.ko

Message from syslogd@mytest at Jun 4 19:31:02 ...
kernel:byebye!
#
[/code]

tailf /var/log/messages
查看日志

obj-m 意思是将后面跟的东西编译成内核模块。相对应还有:
obj-y 编译进内核
obj-n 不编译

hello.o 为模块名称
hello.o-objs 为模块依赖的文件名
KID 指定了内核源码的路径
PWD
为当前路径
-C 选项的作用是指将当前工作目录转移到你所指定的位置。
“M=”
选项的作用是,当用户需要以某个内核为基础编译一个外部模块的话,
需要在make modules 命令中加入“M=dir”,程序会自动到你所指定的dir目录中查找模块源码,
将其编译,生成KO文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值