1. 编写一个简单的字符设备框架
*****hello.c*****
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
static int hello_init(void)
{
printk("hello world!\n"); //简单打印
return 0;
}
static void hello_exit(void)
{
printk("bye!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL"); //协议,如果没有协议可能编译出错
问:如何告诉内核,我这个驱动程序的入口在哪里?
答:使用module_init()函数告诉内核是hello_init()入口函数,module_exit()是出口函数
这样我们就编写了人生第一个linux驱动程序。
2.编译,运行我们第一个驱动程序
需要编写一个makefile文件
*****Makefile*****
KERN_DIR = /usr/src/linux-2.6.22.6
all:
make -C $(KERN_DIR) M=`pwd` modules
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order
obj-m += hello.o
这里我要多说几句,请保持要运行这个驱动程序的内核版本一致,这里我的用到的版本是2.6.22.6,如果发现你的程序明明没有什么很大的问题,但是就是在insmod的时候出现错误,那就很有可能是你的驱动程序用到的内核和你开发板上的内核版本不一样。
3.在ubuntu上执行make命令
root@richie:/home/book/drvice/hello# make
make -C /usr/src/linux-2.6.22.6 M=`pwd` modules
make[1]: Entering directory `/usr/src/linux-2.6.22.6'
CC [M] /home/book/drvice/hello/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/book/drvice/hello/hello.mod.o
LD [M] /home/book/drvice/hello/hello.ko
make[1]: Leaving directory `/usr/src/linux-2.6.22.6'
生成hello.ko文件,把ko文件拷贝到开发板上
4.在开发板终端上使用命令
insmod hello.ko
输出:hello world!