Mmap system call operation that is able to access memory locations

一笑奈何 提交于 2020-01-11 09:54:06

问题


I am writing a program that allocates huge chunks of memory using mmap and then accesses random memory locations to read and write into it. I just tried out the following code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main() {
    int fd,len=1024*1024;
         fd=open("hello",O_READ);
    char*addr=mmap(0,len,PROT_READ+PROT_WRITE,MAP_SHARED,fd,0);
    for(fd=0;fd<len;fd++)
putchar(addr[fd]);

    if (addr==MAP_FAILED) {perror("mmap"); exit(1);}

    printf("mmap returned %p, which seems readable and writable\n",addr);
    munmap(addr,len);

    return 0;
}

But I cannot execute this program, is there anything wrong with my code?


回答1:


First of all, the code won't even compile on my debian box. O_READ isn't a correct flag for open() as far as I know.

Then, you first use fd as a file descriptor and the you use it as a counter in your for loop.

I don't understand what you're trying to do, but I think you misunderstood something about mmap.

mmap is used to map a file into the memory, this way you can read / write to the created memory mapping instead of using functions to access the file.

Here's a short program that open a file, map it the the memory and print the returner pointer :

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main() {
    int fd;
    int result;
    int len = 1024 * 1024;

    fd = open("hello",O_RDWR | O_CREAT | O_TRUNC, (mode_t) 0600);
    // stretch the file to the wanted length, writting something at the end is mandatory
    result = lseek(fd, len - 1, SEEK_SET);
    if(result == -1) { perror("lseek"); exit(1); }
    result = write(fd, "", 1);
    if(result == -1) { perror("write"); exit(1); }

    char*addr = mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr==MAP_FAILED) { perror("mmap"); exit(1); }

    printf("mmap returned %p, which seems readable and writable\n",addr);
    result = munmap(addr, len);
    if (result == -1) { perror("munmap"); exit(1); }

    close(fd);
    return 0;
}

I left out the for loop, since I didn't understood its purpose. Since you create a file and you want to map it on a given length, we have to "stretch" the file to the given length too.

Hope this helps.



来源:https://stackoverflow.com/questions/5178988/mmap-system-call-operation-that-is-able-to-access-memory-locations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!