2012-02-13 121 views
4

我需要在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个链接。

回答

4

您应该测试mmap的结果。如果它给出MAP_FAILED查看errno找出原因。

你会更好的mmap页的整数倍,每个经常4K字节,并给予通过sysconf(_SC_PAGESIZE)

您可以使用stat找出的大小(约许多其他数字)的一些指定的文件。

你可以在现有的Linux程序上使用strace来了解他们在做什么系统调用。

又见this/proc/

+1

谢谢你的帮助,我发现我写的文件写保护,因为这一切都失败了。 – RobbingDaHood 2012-02-14 13:58:54

1

scanf()调用应该是sscanf(),和第二敞开应该使用"mapTester"代替argv[1]作为文件名。当我修复这些错误时,您的发布程序就会运行(打印出22并在文件中保留44)。

+0

我无法让代码与您所说的更改一起工作。我不知道如何在评论中格式化代码,所以我只是把它放在消息的末尾。我使用g ++编译器命令,也许你正在使用另一个? – RobbingDaHood 2012-02-14 13:39:36

+0

好吧我不能添加更多的代码,因为它太长了。我复制了我在这里写的代码,并更改了2个地方,并在代码的最后部分出现了分段错误。但谢谢你的好消息,非常有帮助:) – RobbingDaHood 2012-02-14 13:41:02

相关问题