linux驱动编写(字符设备编写框架)
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
#include <stdio.h>#include <fcntl.h>#include <unistd.h>#define MEM_CLEAR 0x01#define CHAR_DEV_NAME "/dev/chr_dev"int main(){ int ret; int fd; int index; char buf[32];/* open device */ fd = open(CHAR_DEV_NAME, O_RDWR | O_NONBLOCK); if(fd < 0) { printf("open failed!\n"); return -1; }/* set buffer data, which will be stored into device */ for(index = 0; index < 32; index ++) { buf[index] = index; }/* write data */ write(fd, buf, 32); memset(buf, 0, 32);/* read data */ lseek(fd, 0, SEEK_SET); read(fd, buf, 32); for(index = 0; index < 32; index ++) { printf("data[%d] = %d\n", index, buf[index]); }/* reset all data to zero, read it and check whether it is ok */ioctl(fd, MEM_CLEAR, NULL);lseek(fd, 0, SEEK_SET); read(fd, buf, 32); for(index = 0; index < 32; index ++) { printf("data[%d] = %d\n", index, buf[index]); } close(fd); return 0;} 细心的朋友可能发现了,我们在用户侧代码中使用了很多的处理函数,基本上从open、release、read、write、lseek、ioctl全部包括了。测试代码处理的流程也非常简单,首先打开设备,接着写数据,后面就是读取数据,最后利用ioctl清除数据,程序返回。因为代码中包含了注释的内容,在此我们就不过多赘述了。大家慢慢看代码,应该都会了解和明白的。