Mmap system call operation capable of accessing memory cells

I am writing a program that allocates huge chunks of memory using mmap and then accesses random memory cells to read and write to it. I just tried 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 can’t run this program, is there something wrong with my code?

+3
source share
1 answer

First of all, the code will not even compile in my debian field. As far as I know, O_READ is not the right flag for open ().

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

I do not understand what you are trying to do, but I think that you did not understand something about mmap.

mmap , / .

, , :

#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;
}

for, . , "" .

, .

+8

Source: https://habr.com/ru/post/1795992/


All Articles