简体   繁体   English

为什么我不能写入mmaped文件

[英]Why can't I write to the file mmaped

First I create a file and echo some characters to it, and cat the file it shows: 首先,我创建一个文件并将一些字符回显给它,然后捕获它显示的文件:

sasdfasdfas sasdfasdfas

asfdasfsadf asfdasfsadf

Then in the C program, I open the file with : 然后在C程序中,我打开文件:

int fd=open("file",O_RDWR);

mmaped the file with: mmaped文件:

unsigned char *addr=mmap(NULL,length,PROT_WRITE,MAP_PRIVATE,fd,pa_offset);

where length is a int about the size of the file abtained by fstat, and pa_offset is 0. 其中length是关于fstat获取的文件大小的int,pa_offset是0。

The open function and mmap function all return well, that are, the open returns a positive integer like 3, and the mmap returns a proper address like 0x7fd36999d000. open函数和mmap函数都返回良好,即open返回一个像3这样的正整数,mmap返回一个正确的地址,如0x7fd36999d000。

I read the file from the addr and everything is OK. 我从addr读取文件,一切正常。 When I write to it, it seems write succesfully as I print the memory in the program, but the actual file content is not changed if I cat it. 当我写它时,似乎在我打印程序中的内存时成功写入,但是如果我捕获它,实际的文件内容不会改变。

I have tried some efforts like using msync(), but all have the same result. 我尝试了一些像使用msync()的努力,但都有相同的结果。

Who of you would be kind to tell me where I was stumbled? 你们谁会好心地告诉我在哪里被绊倒了? I just want to write to the file from mmap-_- 我只是想从mmap -_-写入文件

You want MAP_SHARED rather than MAP_PRIVATE . 您想要MAP_SHARED而不是MAP_PRIVATE

unsigned char *addr=mmap(NULL,length,PROT_WRITE,MAP_PRIVATE,fd,pa_offset);
                                                ↑↑↑↑↑↑↑↑↑↑↑

From the GNU C library manual (emphasis mine): GNU C库手册 (强调我的):

MAP_PRIVATE - This specifies that writes to the region should never be written back to the attached file. MAP_PRIVATE - 指定不应将对区域的写入写回附加文件。 Instead, a copy is made for the process, and the region will be swapped normally if memory runs low. 而是为该进程创建一个副本,如果内存不足,该区域将正常交换。 No other process will see the changes. 没有其他过程会看到更改。

MAP_SHARED - This specifies that writes to the region will be written back to the file. MAP_SHARED - 指定对区域的写入将写回文件。 Changes made will be shared immediately with other processes mmaping the same file. 所做的更改将立即与其他进程共享同一文件。 Note that actual writing may take place at any time. 请注意,实际写作可能随时进行。 You need to use msync , described below, if it is important that other processes using conventional I/O get a consistent view of the file. 如果使用传统I / O的其他进程获得文件的一致视图很重要,则需要使用下面描述的msync

See man mmap . man mmap

Put another way, MAP_PRIVATE divorces the mapped memory from the backing file by using copy-on-write . 换句话说, MAP_PRIVATE通过使用copy-on-write将映射的内存与后备文件MAP_PRIVATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM