linux驱动helloworld

环境:centOS5;x86_64

[root@test include]# uname -r
2.6.18-308.8.2.el5

首先构建一个内核树:上http://www.kernel.org/pub/linux/kernel/ 找对应版本。下载 解压到/usr/src/目录

#cd /tmp
#wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.18.tar.bz2
#tar jxvf linux-2.6.18.tar.bz2 -C /usr/src/

把usr/include/里的asm linux scsi重定向到新下载的内核中

#rm -rf /usr/include/asm  /usr/include/linux /usr/include/scsi
#ln -s /usr/src/linux-2.6.18/include/asm-x86_64 /usr/include/asm
#ln -s /usr/src/linux-2.6.18/include/linux /usr/include/linux
#ln -s /usr/src/linux-2.6.18/include/scsi /usr/include/scsi

开始编译

#cd /usr/src/linux-2.6.18
#make mrproper
#make defconfig
#make 
#make modules
#make modules_install
#make install

编译完成。可以make help | less看make选项的意思

开始helloworld

#cd
#mkdir -p /dv/hello
#cd /dv/hello
#vi hello.c

hello.c

#include <linux/init.h>
#include <linux/module.h>

MODULE_LICENSE("DUAL BSD/GPL");

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

static void hello_exit(void) {
   printk(KERN_ALERT "dv_goodbye\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile 

obj-m := hello.o
PWD := $(shell pwd)
KVER := $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
   $(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
   rm -f *.o *.ko *.mod.c .hello*

make一下生成一堆文件

[root@test hello]# ls
hello.c   hello.mod.c  hello.o   Module.markers
hello.ko  hello.mod.o  Makefile  Module.symvers

 

加载模块和卸载模块

#insmod ./hello.ko
#rmmod hello

看看日志#cat /var/log/messages,可以看到hello.ko打印出的信息

Nov  8 17:47:35 test kernel: hello world
Nov  8 17:47:38 test kernel: goodbye

为了效果更明显可以用tmux分出一个屏用watch -n 1 tail -n 3 /var/log/messages 或者tail -f /var/log/messages来监视日志输出

转载于:https://www.cnblogs.com/Leo-Forest/archive/2012/11/14/2770741.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值