mmap系统调用的操作,能够访问存储位置 [英] Mmap system call operation that is able to access memory locations

查看:151
本文介绍了mmap系统调用的操作,能够访问存储位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的分配使用mmap内存大块的程序,然后随机存取存储器位置读取和写入进去。
 我只是尝试了以下code:

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

但我不能执行这个程序,是有什么问题我的code?

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

推荐答案

首先,在code甚至不会编译在我的Debian框。 O_READ不开放()据我知道一个正确的标记。

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.

然后,你第一次使用 FD 作为文件描述符和使用它作为一个计数器在for循环。

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

我不明白你想要做什么,但我想你是误会一些关于 MMAP

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

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.

希望这有助于。

这篇关于mmap系统调用的操作,能够访问存储位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆