mmap设备文件操作

x33g5p2x  于2022-05-16 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(456)

linux内核笔记(五)高级I/O操作(三)

内容如上写好的

这里分析下驱动的测试程序

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/mman.h>
  6. #include <string.h>
  7. int main(int argc, char * argv[])
  8. {
  9. int fd;
  10. char *start;
  11. int i;
  12. char buf[32];
  13. fd = open("/dev/vfb0", O_RDWR);
  14. if (fd == -1)
  15. goto fail;
  16. //调用了mmap系统调用,第一个参数是映射的起始地址(通常为NULL由内核来决定),第二个参数32是要映射的内存空间的大小,第三个参数 PROT_READ | PROT_WRITE表示映射后的空间是可读、可写的,第四个参数是多进程共享,最后一个参数是位置偏移量,0表示从头开始
  17. start = mmap(NULL, 32, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  18. if (start == MAP_FAILED)
  19. goto fail;
  20. //直接对映射之后的内存的操作
  21. for (i = 0; i < 26; i++)
  22. *(start + i) = 'a' + i;
  23. *(start + i) = '\0';
  24. if (read(fd, buf, 27) == -1)
  25. goto fail;
  26. puts(buf);
  27. munmap(start, 32);
  28. return 0;
  29. fail:
  30. perror("mmap test");
  31. exit(EXIT_FAILURE);
  32. }

代码第19行

  1. start = mmap(NULL, 32, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

调用了mmap系统调用,第一个参数是想要映射的起始地址,通常设置为NULL,表示由内核来决定该起始地址。第二个参数32是要映射的内存空间的大小。第三个参数PROT_ READ| PROT_ WRITE表示映射后的空间是可读、可写的。第四个参数MAP_ SHARED是指映射是多进程共享。最后一个参数是位置偏移,为0表示从头开始。

  1. for (= 0; i < 26; i++)
  2.         *(start + i) = 'a' + i;
  3.    *(start + i) = '\0';

代码第23行至第25行是直接对映射之后的内存进行操作。

  1. if (read(fd, buf, 27) == -1)
  2.        goto fail;

代码第27行则读出之前操作的内容,可对比判断操作是否成功。下面是编译、测试用的命令。

  1. #mknod /dev/vfb c 256 1
  2. #gcc -c test test.c
  3. #make
  4. #make modules_install
  5. #depmod
  6. #rmmod vfb
  7. #modprobe vfb
  8. #./test
  9. abcdefghijklmnopqrstuvwxyz

相关文章