2011-03-03 60 views
3

我正在编写一个程序,它使用mmap分配大量内存,然后访问随机内存位置来读取和写入内存。 我只是尝试了下面的代码:Mmap系统调用操作能够访问内存位置

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

但我不能执行这个程序,是有什么错我的代码?

回答

8

首先,代码甚至不会在我的debian框中编译。就我所知,O_READ不是open()的正确标志。

然后,您首先使用fd作为文件描述符,并将其用作for循环中的计数器。

我不明白你想要做什么,但我想你误解了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循环,因为我没有理解它的目的。既然你创建了一个文件,并且你想将它映射到一个给定的长度上,我们也必须将文件“拉伸”到给定的长度。

希望这会有所帮助。