新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > 嵌入式Linux设备驱动开发之:实验内容——test驱动

嵌入式Linux设备驱动开发之:实验内容——test驱动

作者:时间:2013-09-13来源:网络收藏

本文引用地址:http://www.eepw.com.cn/article/257106.htm

11.7实验内容——

1.实验目的

该实验是编写最简单的字符驱动程序,这里的设备也就是一段内存,实现简单的读写功能,并列出常用格式的Makefile以及驱动的加载和卸载脚本。读者可以熟悉字符的整个编写流程。

2.实验内容

该实验要求实现对虚拟设备(一段内存)的打开、关闭、读写的操作,并要通过编写测试程序来测试虚拟设备及其驱动运行是否正常。

3.实验步骤

(1)编写代码。

这个简单的驱动程序的源代码如下所示:

/*test_drv.c*/

#includelinux/module.h>

#includelinux/init.h>

#includelinux/fs.h>

#includelinux/kernel.h>

#includelinux/slab.h>

#includelinux/types.h>

#includelinux/errno.h>

#includelinux/cdev.h>

#includeasm/uaccess.h>

#defineTEST_DEVICE_NAMEtest_dev

#defineBUFF_SZ1024

/*全局变量*/

staticstructcdevtest_dev;

unsignedintmajor=0;

staticchar*data=NULL;

/*读函数*/

staticssize_ttest_read(structfile*file,

char*buf,size_tcount,loff_t*f_pos)

{

intlen;

if(count0)

{

return-EINVAL;

}

len=strlen(data);

count=(len>count)?count:len;

if(copy_to_user(buf,data,count))/*将内核缓冲的数据拷贝到用户空间*/

{

return-EFAULT;

}

returncount;

}

/*写函数*/

staticssize_ttest_write(structfile*file,constchar*buffer,

size_tcount,loff_t*f_pos)

{

if(count0)

{

return-EINVAL;

}

memset(data,0,BUFF_SZ);

count=(BUFF_SZ>count)?count:BUFF_SZ;

if(copy_from_user(data,buffer,count))/*将用户缓冲的数据复制到内核空间*/

{

return-EFAULT;

}

returncount;

}

/*打开函数*/

staticinttest_open(structinode*inode,structfile*file)

{

printk(Thisisopenoperationn);

/*分配并初始化缓冲区*/

data=(char*)kmalloc(sizeof(char)*BUFF_SZ,GFP_KERNEL);

if(!data)

{

return-ENOMEM;

}

memset(data,0,BUFF_SZ);

return0;

}

/*关闭函数*/

staticinttest_release(structinode*inode,structfile*file)

{

printk(Thisisreleaseoperationn);

if(data)

{

kfree(data);/*释放缓冲区*/

data=NULL;/*防止出现野指针*/

}

return0;

}

/*创建、初始化字符设备,并且注册到系统*/

staticvoidtest_setup_cdev(structcdev*dev,intminor,

structfile_operations*fops)

{

interr,devno=MKDEV(major,minor);

cdev_init(dev,fops);

dev->owner=THIS_MODULE;

dev->ops=fops;

err=cdev_add(dev,devno,1);

if(err)

{

printk(KERN_NOTICEError%daddingtest%d,err,minor);

}

}

linux操作系统文章专题:linux操作系统详解(linux不再难懂)

linux相关文章:linux教程



上一页 1 2 3 4 下一页

评论


相关推荐

技术专区

关闭