linux的module的“hello world”程序

终于看到使用module的hello world了,哈哈哈

我使用的是Ubuntu10.04-64位的Desktop

 

建立源文件hello.c和Makefile:

hello.c

#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk("Hello, world/n");
return 0;
}
static void hello_exit(void)
{
printk("Goodbye, cruel world/n");
}
module_init(hello_init);
module_exit(hello_exit);

 

Makefile:

obj-m := hello.o

 

源文件建好之后,用如下命令编译:

# make -C /usr/src/linux-headers-2.6.32-21-generic/ SUBDIRS=$PWD modules

编译的结果如下:

hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers

 

{

也可以这样来编译

Makefile:

# If KERNELRELEASE is defined, we've been invoked from the
# kernel build system and can use its language.
ifneq ($(KERNELRELEASE),)
        obj-m := hello.o
# Otherwise we were called directly from the command
# line; invoke the kernel build system.
else
        KERNELDIR ?= /lib/modules/$(shell uname -r)/build
        PWD := $(shell pwd)
default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
然后运行 make 编译即可(不用带任何参数)

}

 

把hello.ko加载到内核中:

# insmod hello.ko

用lsmod或者查看文件/proc/modules可以发现"hello"已经被加载到内核中

 

把hello.ko从内核中移除:

# rmmod hello

再运行lsmod就会发现已经被移除了

 

查看/var/log/messages可以得到这个过程的打印信息,"Hello, world"出现啦!

# cat /var/log/messages
May 12 01:26:01 ubuntu rsyslogd: [origin software="rsyslogd" swVersion="4.2.0" x-pid="722" x-info="http://www.rsyslog.com"] rsyslogd was HUPed, type 'lightweight'.
May 12 01:42:51 ubuntu kernel: [ 2516.713810] Hello, world
May 12 01:42:59 ubuntu kernel: [ 2524.553781] Goodbye, cruel world

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值