能够访问内存位置的 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;
}
但是我无法执行该程序,我的代码有什么问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,代码甚至无法在我的 debian 机器上编译。据我所知,O_READ 不是 open() 的正确标志。
然后,您首先使用
fd
作为文件描述符,然后将其用作 for 循环中的计数器。我不明白你想做什么,但我认为你误解了
mmap
的一些内容。mmap
用于将文件映射到内存中,这样您就可以读取/写入创建的内存映射,而不是使用函数来访问文件。这是一个简短的程序,它打开一个文件,将其映射到内存并打印返回指针:
我省略了 for 循环,因为我不明白它的用途。由于您创建了一个文件并且希望将其映射到给定长度,因此我们也必须将文件“拉伸”到给定长度。
希望这有帮助。
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 :
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.