Linux MMAP Learning
In the past, MMAP was very simple. After reading the parameter usage, it was okay. The results encountered a lot of trouble. Many Google Blogs were quite simple, let's just introduce the parameters and then give me a simple code, so it's over, so I am struggling for almost a day.
MMAP won't be used for me anymore. There are a lot of web pages. Here I will share my mistakes and post the code for copying arbitrary files with MMAP:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <unistd.h>#include <fcntl.h>#include <sys/mman.h>#include <sys/stat.h>#include <sys/types.h>int main(){int fdin,fdout, len = 0, pages = 0, offset = 0, lastPage = 0;char *src, *dst;size_t pagesize;struct stat statbuf;if((fdin = open("mmmap.c", O_RDWR)) == -1){printf("can't open fdin ");return 1;}if((fdout = open("mmmmap1.c",O_RDWR | O_CREAT | O_TRUNC,0644)) == -1){if(EEXIST == errno){fd = open("mmmmap1.c", O_RDWR);if(-1 == fd){perror("open");exit(-1);}}else{perror("open");exit(-1);}}//lseek(fd, 4096, SEEK_SET);//write(fd, " ", 1);pagesize = sysconf(_SC_PAGESIZE);printf("pagesize = %ld\n", pagesize);assert(fstat(fdin,&statbuf) == 0);printf("statbuf.st_size = %d\n", statbuf.st_size);pages = statbuf.st_size/pagesize;if((statbuf.st_size)%pagesize != 0){lastPage = (statbuf.st_size)%pagesize;pages += 1;printf("lastPage = %d\n", lastPage);}printf("pages = %d\n", pages);//assert(ftruncate(fdout, statbuf.st_size) == 0);if (lastPage != 0){len += lastPage;}else{len += pagesize;}while(pages--){assert(ftruncate(fdout, len) == 0);src = (char *)mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fdin, offset);if( src == MAP_FAILED ){printf("mmap error for fdin.\n");return 1;}dst = mmap(0,pagesize,PROT_READ | PROT_WRITE,MAP_SHARED,fdout,offset);if( dst == MAP_FAILED ){printf("mmap error for fdout.\n");return 1;}memcpy(dst,src, pagesize);offset += pagesize;if (pages == 1 && lastPage != 0){len += lastPage;}else{len += pagesize;}munmap(src, pagesize);munmap(dst, pagesize);}close(fdin);close(fdout);return 0;}
My problems:
1. A segment error is reported. If the read/write mode is different from the parameter in MMAP, this error is reported.
2. Bus error. The file is empty, or the MMAP page is displayed, but you have to operate the second page.
3. the newly created Write File may open an exception sometimes because no characters should be written to the file during MMAP. Therefore, we recommend that you do not use write when updating the file size, and use ftruncate.
Remember that MMAP maps one page at a time. The Len and offset parameters are only page multiples...
If you have any questions, please leave a message to discuss them ..... Pai_^