以下均是在X86平台下编辑,操作,运行
编写好驱动,通过挂载的方法将驱动程序挂载到内核里面,大致步骤如下:
一:
2>建立Makefile文件(作用是通过make来产生设备文件*.ko文件,里面可以建立自己的平台所需的设备文件如:arm等).make 产生相应的设备文件
二: 要在/dev下建立相应的设备结点(设备名),用insomd *.ko命令将相应的驱动设备文件挂载到内核中.
三:编写测试文件(.c文件)用来测试内核是否已近成功挂载到内核.(编写好相应的测试文件后,用gcc –o Filename Filename.c(测试文件名) 来产生相应的可执行文件).
四:如果设备驱动挂载成功,当执行测试文件(./Filename)时会产生相应的结果.
五:可能用到的相关命令:
1.
输出:
Module(模块名)
2.
3.
4.
5.
6.
7.
8.
六.例子1:
第一步:增加头文件和宏定义
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/module>
#include <linux/kernel>
第二步:添加与字符设备定义及注册有关的数据成员
//定义设备名称
#define DEVICE_NAME "test"
#define BUF_SIZE
static char tmpbuf[BUF_SIZE];
//定义主次设备号
static unsigned int TestMajor=0;
static unsigned int TestMinor=0;
static struct cdev *test_cdev;
static dev_t dev;
第三步:增加open/release函数
static int test_chardev_open(struct inode *inode,struct file *file)
{
}
static int test_chardev_release(struct inode *inode,struct file *file)
{
}
第四步:增加read函数
static ssize_t test_chardev_read(struct file *file,char __user *buf,
{
}
}
第五步:增加write函数
static ssize_t test_chardev_write(struct file *file, const char __user
{
}
}
第六步:添加增加file_operations 成员
static struct file_operations chardev_fops={
};
第七步:在模块的入口添加设备的设备号获取及设备注册
static int __init chrdev_init(void)
{
int result;
if(TestMajor)
{
} else {
}
if(result<0)
{
}
test_cdev=cdev_alloc();
cdev_init(test_cdev,&chardev_fops);
//test_cdev->ops=&chardev_fops;
test_cdev->owner=THIS_MODULE;
result=cdev_add(test_cdev,dev,1);
if(result)
return 0;
}
第八步:在模块的出口函数增加设备设备号释放及设备注销函数
第九步:编译并加载该模块
第十步:根据设备号的设置,在文件系统中建立对应的设备节点
例子2:
驱动文件:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/uaccess.h>
#define DEVICENAME
unsigned int major=221;
unsigned int minor=0;
struct cdev *abc;
dev_t dev;
static char bufrh[1024]="read success!";
static int aaaaa_open(struct inode *inodep, struct file *filep)
{
}
int aaaaa_release(struct inode *inodep, struct file *filep)
{
}
static ssize_t aaaaa_read (struct file *filep, char __user *buf, size_t
{
}
ssize_t aaaaa_write (struct file *filep, const char __user *buf,
{
}
static const struct
};
static int __init aaaaa_init(void)
{
}
static void __exit
{
}
module_init(aaaaa_init);
module_exit(aaaaa_cleanup);
MODULE_LICENSE("GPL ");
Makefile文件:
obj-m += firstqd.o(相应设备文件名)
KERDIR = /usr/src/linux-headers-2.6.32-24-generic
#KERDIR=/home/linux2.6/linux
PWD=$(shell pwd)
modules:
pc:
arm:
clean:
测试文件(test.c):
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
char buf[1024];
char bufw[1024]="write success";
int main()
{
}