我需要在Linux中使用mmap()进行一些流入和输出类。为此,我尝试制作一些测试代码,将一些整数写入文件,保存它,再次加载并将文件中的数据写入到文件中。如果这个测试代码有效,那么它不会成为一个问题。如何在Linux系统上使用mmap()进行读取和写入
当我第一次开始时,我得到了段错误,如果我没有发现任何事情发生,所以我GOOGLE了一下。我发现这本书http://www.advancedlinuxprogramming.com/alp-folder/alp-ch05-ipc.pdf其中第107页左右有一些有用的代码。我复制粘贴代码,并做了一些小的变化,并得到这个代码:
int fd;
void* file_memory;
/* Prepare a file large enough to hold an unsigned integer. */
fd = open ("mapTester", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
//Make the file big enough
lseek (fd, 4 * 10 + 1, SEEK_SET);
write (fd, "", 1);
lseek (fd, 0, SEEK_SET);
/* Create the memory mapping. */
file_memory = mmap (0, 4 * 10, PROT_WRITE, MAP_SHARED, fd, 0);
close (fd);
/* Write a random integer to memory-mapped area. */
sprintf((char*) file_memory, "%d\n", 22);
/* Release the memory (unnecessary because the program exits). */
munmap (file_memory, 4 * 10);
cout << "Mark" << endl;
//Start the part where I read from the file
int integer;
/* Open the file. */
fd = open (argv[1], O_RDWR, S_IRUSR | S_IWUSR);
/* Create the memory mapping. */
file_memory = mmap (0, 4 * 10, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
close (fd);
/* Read the integer, print it out, and double it. */
scanf ((char *) file_memory, "%d", &integer);
printf ("value: %d\n", integer);
sprintf ((char*) file_memory, "%d\n", 2 * integer);
/* Release the memory (unnecessary because the program exits). */
munmap (file_memory, 4 * 10);
但我的“标志” COUT后得到了段富尔茨。
然后我代替这个“阅读部分”:
fd = open("mapTester", O_RDONLY);
int* buffer = (int*) malloc (4*10);
read(fd, buffer, 4 * 10);
for(int i = 0; i < 1; i++)
{
cout << buffer[i] << endl;
}
那就是让我发现,该文件是空的一些工作的代码。我尝试了几种写入映射的方式,而不会改变结果。
那么我怎样才能让我的代码写入? 我的mmap阅读代码看起来好吗(以防万一你可以看到一些明显的缺陷)?
我发现了一些其他资源,但没有帮助我,但因为我是一个新用户,我可能只发布最多2个链接。
谢谢你的帮助,我发现我写的文件写保护,因为这一切都失败了。 – RobbingDaHood 2012-02-14 13:58:54