可以访问内存位置的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; } 

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

首先,代码甚至不会在我的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; } 

我遗漏了循环,因为我不明白它的目的。 既然你创建了一个文件,并且想要将它映射到一个给定的长度,我们也必须将文件“拉伸”到给定的长度。

希望这可以帮助。