Why can't I write to mmaped file

First I create a file and iterate some characters to it, and cat is the file it shows:

sasdfasdfas

asfdasfsadf

Then, in C program, I open the file with:

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

      

mmaped file:

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

      

where length is an int with the file size supported by fstat and pa_offset is 0.

The open and mmap functions all return well, that is, open returns a positive integer like 3, and mmap returns the correct address, such as 0x7fd36999d000.

I read the file from addr and everything is fine. When I write to it, it seems that the write succeeds when I print the memory in the program, but the actual content of the file does not change if I do it.

I've tried some attempts at using msync () but they all have the same result.

How many of you would be kind to tell me where I stumbled? I just want to write a file from mmap -_-

+3


source to share


1 answer


You want MAP_SHARED

, not MAP_PRIVATE

.

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

      

From the GNU C Library Manual (attention):



MAP_PRIVATE

- Specifies that write to area should never be written back to the attached file. Instead, a copy is made for the process, and the area will change normally if the memory is low. No other process will see the change.

MAP_SHARED

- Indicates that records in the area will be written back to file. The changes made will be immediately passed on to other processes the same file. Please note that the actual letter may take place at any time. You should use the msync

one described below if it is important that other processes using normal I / O get a consistent view of the file.

See man mmap

.

In other words, it MAP_PRIVATE

splits the mapped memory out of the backup file using copy-on-write .

+6


source







All Articles