hello world开始

本文介绍了一个简单的Linux内核模块开发实例,包括模块的初始化与退出过程,并提供了makefile配置及模块编译、加载、卸载的方法。通过查看系统日志验证模块功能。

下面的代码是一个完整的 "hello world"模块:

#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 "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);
然后是makefile 注意2.6的内核只能用makefile编译模块
  1 # If KERNELRELEASE is defined, we've been invoked from the
  2 # kernel build system and can use its language.
  3 ifneq ($(KERNELRELEASE),)
  4 
  5  obj-m := hello.o
  6 # Otherwise we were called directly from the command
  7 # line; invoke the kernel build system.
  8 else
  9     KERNELDIR ?= /lib/modules/$(shell uname -r)/build
 10     PWD := $(shell pwd)
 11 default:
 12     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
 13 
 14 endif

操作:
make
可以看到产生了
hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers
加载:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ sudo insmod ./hello.ko 
移除:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ sudo rmmod hello 
查看日志:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ tail -2 /var/log/kern.log 
Jul 18 10:52:20 ubuntu kernel: [13235.917043] Hello, world
Jul 18 10:52:25 ubuntu kernel: [13241.282165] Goodbye, cruel world


                
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值