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

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);


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值