Accessing physical address from user space

2690阅读 0评论2017-11-23 wibnmo
分类:C/C++


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <sys/mman.h>
  5. #include <unistd.h>

  6. int main(int argc, char *argv[]) {
  7.     if (argc < 3) {
  8.         printf("Usage: %s \n", argv[0]);
  9.         return 0;
  10.     }

  11.     off_t offset = strtoul(argv[1], NULL, 0);
  12.     size_t len = strtoul(argv[2], NULL, 0);

  13.     // Truncate offset to a multiple of the page size, or mmap will fail.
  14.     size_t pagesize = sysconf(_SC_PAGE_SIZE);
  15.     off_t page_base = (offset / pagesize) * pagesize;
  16.     off_t page_offset = offset - page_base;

  17.     int fd = open("/dev/mem", O_SYNC);
  18.     unsigned char *mem = mmap(NULL, page_offset + len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, page_base);
  19.     if (mem == MAP_FAILED) {
  20.         perror("Can't map memory");
  21.         return -1;
  22.     }

  23.     size_t i;
  24.     for (i = 0; i < len; ++i)
  25.         printf("%02x ", (int)mem[page_offset + i]);

  26.     return 0;
  27. }

Accessing physical address from user space
上一篇:wakelock实现
下一篇:tmux配置