Linux应用层操作寄存器

描述

应用层操作寄存器

驱动中操作寄存器,需要先进行映射将物理地址转为虚拟地址。

但如果想在应用层中操作寄存器,也是可以实现的。

应用层中只需打开/dev/mem设备节点,然后用mmap映射寄存器地址就可以访问了。

例如,应用层读取物理地址为0x40000000的值:

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

#define MAP_SIZE 0x80000
#define base 0x40000000

int main(int argc, char **argv)
{
  int fd = open("/dev/mem",O_RDWR|O_NDELAY);
    if (fd < 0)
    {
        printf("open /dev/mem error!n");
        return -1;
  }
    
    void *map_base = mmap(NULL,MAP_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,base);
    if (map_base == MAP_FAILED)
    return -1;
    
    printf("%x n",*(volatile unsigned int*)(map_base));

    close(fd);
    munmap(map_base,MAP_SIZE);
    
  return 0;
}

注意,内核必须将CONFIG_STRICT_DEVMEM=y配置选项打开才有/dev/mem节点

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分