- 论坛徽章:
- 0
|
目标:在Linux系统下写出第一个驱动程序
平台:fedora 7.0
书籍:《Linux Device drivers》
简介:
就是学习各种语言的编程一样,第一个要编写的程序都是hello world。Linux下的驱动程序,也是从hello world开始写起的。需要完成的工作包括:源代码的编写、编写Makefile文件、编译和运行。
源代码编写:
在终端环境下,运行vi编写代码,代码如下:
1 #include
2 #include
3
4 MODULE_LICENSE("Dual BSD/GPL");
5
6 static int hello_init(void)
7 {
8 printk(KERN_ALERT "Hello,World\n");
9 return 0;
10 }
11
12 static void hello_exit(void)
13 {
14 printk(KERN_ALERT "Goodbye,cruel world\n");
15 }
16
17 module_init(hello_init);
18 module_exit(hello_exit);
编写Makefile文件:
在编写源代码后,要考虑怎样将源代码编译成能够转载到内核中的可执行模块。这个工作需要编写一个Makefile文件,把源代码编译成可执行的模块。
Makefile文件内容:
#linux derive develop
#makefile
ifneq ($(KERNELRELEASE),)
obj-m :=hello.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
PWD :=$(shell pwd)
default:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
endif
编译与运行:
切换到root用户,在终端的hello.c和Makefile文件所在的目录下运行Make命令,然后演示装载和卸载模块。
命令操作如下:
[root@localhost ldd3]# make
make -C /lib/modules/2.6.21-1.3194.fc7/build SUBDIRS=/home/silentdawn/ldd3 modules
make[1]: Entering directory `/usr/src/kernels/2.6.21-1.3194.fc7-i686'
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/kernels/2.6.21-1.3194.fc7-i686'
[root@localhost ldd3]# insmod ./hello.ko
[root@localhost ldd3]# rmmod hello
注意:在fedora 7.0下insmod命令在/sbin目录下,这个路径不在环境变量PATH中,所以或者用绝对路径来运行insmod,或者在环境变量PATH下添加/sbin路径。添加/sbin路径的方法就是在root用户目录下的.bashrc文件的最后一行添加PATH=/sbin:$PATH,保存退去,运行source .bashrc命令,生效该路径。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/66754/showart_683558.html |
|