您的位置:首页 > 运维架构 > Linux

Linux设备驱动程序代码 第2章 建立和运行模块

2012-12-16 15:12 441 查看

第2章 建立和运行模块

1.资源下载

电子书地址:

pdf版:

http://www.kuaipan.cn/file/id_12008874588517353.htm

chm版:

http://www.kuaipan.cn/file/id_12008874588517352.htm

源码:

http://www.kuaipan.cn/file/id_12008874588520800.htm

Chm版的翻译不太好,pdf的显示不太好。

2.开发环境的搭建

首先地,要装个虚拟机,比如virtualbox,。再装个linux操作系统,可以选ubuntu server。 系统装好后,要装一些驱动开发所需要的软件,运行:

apt-get install build-essential

apt-get install linux-source

这两个软件装好后,环境就搭好了。

3.编写驱动模块

新建一个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 "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);


新建一个Makefile文件,输入下面的内容:

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


注意,换行后的空白符是tab。如果发现make不成功,把空白符换成tab.

4.测试

在控制台上,而不是SecureCRT上,用root用户或者sudo,运行:

insmod ./hello.ko

加载驱动模块,会显示hello,world

运行:

lsmod |grep hello

可以看到所加载的模块。

卸载模块:

rmmod hello




5. 模块参数

//hello.c,Makefile同上
//运行:insmod hello howmany=10 whom="Mom"

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

MODULE_LICENSE("Dual BSD/GPL");

static char *whom = "world";
static int howmany = 1;
module_param(howmany, int, S_IRUGO);
module_param(whom, charp, S_IRUGO);

static int hello_init(void)
{
int i;
for (i = 0; i < howmany; i++)
printk(KERN_ALERT "(%d) Hello, %s\n", i, whom);
return 0;
}

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

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