【发布时间】:2012-03-05 01:06:14
【问题描述】:
我需要在 Linux 中使用 mmap() 创建一些流输入和输出类。为此,我尝试编写一些测试代码,将一些整数写入文件、保存、再次加载并将文件中的数据写入 cout。如果该测试代码有效,那么之后进出流就不会成为问题。
当我第一次开始时,我遇到了段错误,如果我没有发现什么都没有发生,所以我用谷歌搜索了一下。我发现这本书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);
但是我在“mark”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 个链接。
【问题讨论】: