新聞中心

EEPW首頁(yè) > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 嵌入式Linux設(shè)備驅(qū)動(dòng)開(kāi)發(fā)之:實(shí)驗(yàn)內(nèi)容——test驅(qū)動(dòng)

嵌入式Linux設(shè)備驅(qū)動(dòng)開(kāi)發(fā)之:實(shí)驗(yàn)內(nèi)容——test驅(qū)動(dòng)

作者: 時(shí)間:2013-09-13 來(lái)源:網(wǎng)絡(luò) 收藏

本文引用地址:http://2s4d.com/article/257106.htm

11.7實(shí)驗(yàn)內(nèi)容——

1.實(shí)驗(yàn)?zāi)康?/h4>

該實(shí)驗(yàn)是編寫(xiě)最簡(jiǎn)單的字符驅(qū)動(dòng)程序,這里的設(shè)備也就是一段內(nèi)存,實(shí)現(xiàn)簡(jiǎn)單的讀寫(xiě)功能,并列出常用格式的Makefile以及驅(qū)動(dòng)的加載和卸載腳本。讀者可以熟悉字符的整個(gè)編寫(xiě)流程。

2.實(shí)驗(yàn)內(nèi)容

該實(shí)驗(yàn)要求實(shí)現(xiàn)對(duì)虛擬設(shè)備(一段內(nèi)存)的打開(kāi)、關(guān)閉、讀寫(xiě)的操作,并要通過(guò)編寫(xiě)測(cè)試程序來(lái)測(cè)試虛擬設(shè)備及其驅(qū)動(dòng)運(yùn)行是否正常。

3.實(shí)驗(yàn)步驟

(1)編寫(xiě)代碼。

這個(gè)簡(jiǎn)單的驅(qū)動(dòng)程序的源代碼如下所示:

/*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;

/*讀函數(shù)*/

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))/*將內(nèi)核緩沖的數(shù)據(jù)拷貝到用戶空間*/

{

return-EFAULT;

}

returncount;

}

/*寫(xiě)函數(shù)*/

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))/*將用戶緩沖的數(shù)據(jù)復(fù)制到內(nèi)核空間*/

{

return-EFAULT;

}

returncount;

}

/*打開(kāi)函數(shù)*/

staticinttest_open(structinode*inode,structfile*file)

{

printk(Thisisopenoperationn);

/*分配并初始化緩沖區(qū)*/

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

if(!data)

{

return-ENOMEM;

}

memset(data,0,BUFF_SZ);

return0;

}

/*關(guān)閉函數(shù)*/

staticinttest_release(structinode*inode,structfile*file)

{

printk(Thisisreleaseoperationn);

if(data)

{

kfree(data);/*釋放緩沖區(qū)*/

data=NULL;/*防止出現(xiàn)野指針*/

}

return0;

}

/*創(chuàng)建、初始化字符設(shè)備,并且注冊(cè)到系統(tǒng)*/

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操作系統(tǒng)文章專(zhuān)題:linux操作系統(tǒng)詳解(linux不再難懂)

linux相關(guān)文章:linux教程



上一頁(yè) 1 2 3 4 下一頁(yè)

評(píng)論


相關(guān)推薦

技術(shù)專(zhuān)區(qū)

關(guān)閉