开发者

Mmap system call operation that is able to access memory locations

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜