Mmap: a problem occurs when the file is mapped to the memory and the corresponding method on the window. Our program occupies too much memory and crashes when running on the target machine. Some memory can be mapped to files to save some memory. Make a record for future reference. On linux, use mmap: www.2cto.com 1 int dumpFileDescriptor = open (mmFileName, O_CREAT | O_RDWR, 0755); 2 3 if (dumpFileDescriptor! =-1) 4 {5 void * mappedFileAddress = mmap (NULL, 6 MMAP_ALLOCATOR_SIZE, 7 PROT_READ | PROT_WRITE, 8 MAP_SHARED, 9 dumpFileDescriptor, 10 0 ); 11} 12 13 // Do something use mappedFileAddress function msysc can ensure that the data is synchronized to the disk 1 msync (mappedFileAddress, MMAP_ALLOCATOR_SIZE, MS_SYNC); when not needed, use the unmap function to unmap 1 munmap (mappedFileAddress, MMAP_ALLOCATOR_SIZE). Then you can use unlink to delete the ing file. If necessary, 1 unlink (mmFileName); www.2cto.com is searched online. In windows, CreateFileMapping 1 HANDLE dumpFileDescriptor = CreateFileA (mmFileName, 2 GENERIC_READ | GENERIC_WRITE, 3 file_1__read | file_1__write, 4 NULL, 5 OPEN_EXISTING, 6 bytes, 7 NULL ); 8 HANDLE fileMappingObject = CreateFileMapping (dumpFileDescriptor, 9 NULL, 10 PAGE_READWRITE, 11, 13 NULL); 14 void * mappedFileAddress = MapViewOfFile (fileMappingObject, 15 FILE_MAP_AL L_ACCESS, 16, bytes); 19 20 // Do something use mappedFileAddress to synchronize data to disk 1 FlushViewOfFile (mappedFileAddress, volume); un ing www.2cto.com 1 UnmapViewOfFile (mappedFileAddress ); in Windows, if you want to delete the ing file, you must first turn off the file Handle. I didn't know how to delete it at first. 1 CloseHandle (fileMappingObject); 2 CloseHandle (dumpFileDescriptor); 3 unlink (mmFileName );
The running effect of the two platforms is slightly different. On win32, if you apply for 50 MB of memory on heap (nothing else), you can find out after ing the 50 MB memory, when the program is running, the program occupies only a few hundred KB of memory. That is to say, the mapped memory runs into the disk without occupying the memory, provided that you have not accessed the 50 MB space. In Linux, 50 MB of the same program will still be in the memory. Even if you haven't accessed it, it will also have a backup in the memory, but if you apply for a large memory size, such as 100 MB, the memory space is released at MB. I think the possible reason is that on linux, the system will release the memory space mapped to the file only when the memory is insufficient. On windows, if the file is mapped, the memory will be released unless you access it. Author clover24