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

linux2.6驱动编程第一例:hello,world的实现步骤

2010-03-11 15:33 351 查看
按照《linux设备驱动开发详解》一书中的步骤实现经典例子"hello,world!"的例子。具体步骤如下:

遇到的问题:

不知道如何生成.ko内核模块文件,在2.4下,直接#gcc -c hello.c 生成hello.o文件就可以#insmod hello.o,但在2.6中必须生成.ko文件,这又需要你根据具体情况编写Makefile文件。

具体步骤如下
1.编写代码:
/*
* hello.c -- the example of printf "hello world!" in the screen of driver program
*/
#include <linux/init.h>
#include <linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");/* declare the license of the module ,it is necessary */

static int hello_init(void)
{
printk(KERN_ALERT "Hello World enter!/n");
return 0;
}

static int hello_exit(void)
{
printk(KERN_ALERT "Hello world exit!/n");
}

module_init(hello_init); /* load the module */
module_exit(hello_exit); /* unload the module */

/* before is some decription of the model,not necessary */
MODULE_AUTHOR("YJ Hou");
MODULE_DESCRIPTION("This is an example of programming driver!");
MODULE_ALIAS(“a simplest module”);

2.编译代码:
在代码的目录下建立一个Makefile文件,将下面的语句写入其中:
obj-m := hello.o
执行如下命令编译代码:
make -C /home/hyj/linux2.6/ M=/home/hyj/driver/ modules
注意:这里的/home/hyj/linux2.6/是内核源码树的目录,/home/hyj/driver/是你要放置编译文件的目录。我的源文件和编译好的文件都在这个目录下,建议大家要放在同一目录下哦,不然可能出错。
编译完成后将出现下列代码:

[hyj@localhost driver]$ make -C /home/hyj/linux-2.6 M=/home/hyj/driver
make: Entering directory `/home/hyj/linux-2.6'
CC [M] /home/hyj/driver/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/hyj/driver/hello.mod.o
LD [M] /home/hyj/driver/hello.ko
make: Leaving directory `/home/hyj/linux-2.6'

这时就表示编译成功,在目录下将产生hello.ko文件。

3.执行代码,加载驱动模块:
insmod ./hello.ko即可加载模块。
有的朋友可能会出现insmod命令找不到的错误,这可能有下面几个原因:
<1> 你的系统没有安装module-init-tools工具,关于此问题,只需安装即可,但是一般装完系统是有这个命令的。
<2> 环境变量没有添加导致不能使用该命令。使用echo $PATH即可查看PATH环境变量,发现没有/sbin这个路径,所以你当然不能使用insmod这个命令了。解决的方法很简单,只需在命令行输入:
PATH = "$PATH:/sbin"即可添加。(insmod在/sbin这个目录下,你可以使用whereis insmod查看)。
<3> insmod这个命令需要在root权限下才能使用。
加载完成后你可以输入lsmod查看hello这个模块哦。

[root@localhost driver]# insmod ./hello.ko
Message from syslogd@localhost at Apr 15 09:20:03 ...
kernel: Hello,world

4.卸载驱动模块:rmmod hello.

加载模块后就可在屏幕上看到如下信息:Hello world enter.
卸载时就可在屏幕上看到如下信息:hello world exit.

[root@localhost driver]# rmmod hello
[root@localhost driver]#
Message from syslogd@localhost at Apr 15 09:20:47 ...
kernel: Goodbye,cruel world

什么?我执行的时候竟然什么也没有,既没有报错,也没有任何输入?
这时你可以在/var/log/messages这个文件中看到以上输出信息(使用cat /var/log/messages一般在最下面几行)。
那么怎么才能在屏幕上打印出这些信息呢?
这时你必须对源文件做如下修改:
<1> 将"printk(KERN_ALERT "Hello World enter!/n");”一句中的“KERN_ALERT”换成"KERN_EMERG"以提高内核打印的优先级(0);
<2> 同理将printk(KERN_ALERT "Hello world exit!/n");改成printk(KERN_ALERT "Hello world exit!/n");
重新编译,加载,你就可在屏幕上看到输出信息了。
哈哈,总算大功告成了。

另外,如果有多个文件,则按下列方式编写Makefile文件(file1.c、file2.c):
obj -m := modulename.o
module-objs := file1.o file2.o
:0wpoi2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐