Mmap system call operation that is able to access memory locations

后端 未结 1 1340
梦毁少年i
梦毁少年i 2021-01-20 23:54

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:

1条回答
  •  囚心锁ツ
    2021-01-21 00:20

    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 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    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.

    0 讨论(0)
提交回复
热议问题