mmap设备文件操作

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

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

内容如上写好的

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

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>

int main(int argc, char * argv[])
{
    int fd;
    char *start;
    int i;
    char buf[32];

    fd = open("/dev/vfb0", O_RDWR);
    if (fd == -1)
        goto fail;
    //调用了mmap系统调用,第一个参数是映射的起始地址(通常为NULL由内核来决定),第二个参数32是要映射的内存空间的大小,第三个参数 PROT_READ | PROT_WRITE表示映射后的空间是可读、可写的,第四个参数是多进程共享,最后一个参数是位置偏移量,0表示从头开始
    start = mmap(NULL, 32, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (start == MAP_FAILED)
        goto fail;
    //直接对映射之后的内存的操作
    for (i = 0; i < 26; i++)
        *(start + i) = 'a' + i;
    *(start + i) = '\0';

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

    puts(buf);

    munmap(start, 32);
    return 0;

fail:
    perror("mmap test");
    exit(EXIT_FAILURE);
}

代码第19行

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

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

for (i = 0; i < 26; i++)
        *(start + i) = 'a' + i;
   *(start + i) = '\0';

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

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

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

#mknod /dev/vfb c 256 1
#gcc -c test test.c
#make
#make modules_install
#depmod
#rmmod vfb
#modprobe vfb
#./test

abcdefghijklmnopqrstuvwxyz

相关文章

微信公众号

最新文章

更多