Function Prototypes:
void *mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset);
Function: Maps a file to a process memory space with addr as the starting address, and when called, typically passes the addr parameter to NULL, and the kernel chooses the starting virtual address space
The corresponding Munmap (2) system call is de-mapped, and the in-memory data is written to the file. As you can see, after calling Munmap, the pointer returned by MMAP is a wild pointer and cannot access the space it points to.
After Mmap (2) returns, the open file can be closed via close (FD), and the subsequent operation (before Munmap (2) is called) is a memory operation
Program: reprinted from Https://www.ibm.com/developerworks/cn/linux/l-ipc/part5/index1.html
#include <sys/mman.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>#include<stdio.h>#include<string.h>typedefstruct{ Charname[4]; intAge ;} People;intMainintargcChar* * argv)//Map a normal file as shared mem:{ intFd,i; People*P_map; Chartemp; FD=open (argv[1],o_creat| o_rdwr| O_trunc,0777); Lseek (FD,sizeof(People) *5-1, Seek_set); Write (FD,"",1); File size is 5*sizeof (people) = bytes printf ("type people size is%d\n",sizeof(people)); P_map= (people*) mmap (NULL,sizeof(People) *Ten, prot_read|Prot_write, MAP_SHARED,FD,0 ); The mapped memory space size is 10*sizeof (people) close (FD); File temp can be closed via close (2) system call after the file is mapped to memory space='a'; for(i=0; i<Ten; i++) {Temp+=1; memcpy ((* (P_map+i)). Name, &temp,1 ); ( * (P_map+i)). Age = -+i; } printf ("initialize over \ n"); Sleep (Ten); Munmap (P_map,sizeof(People) *Ten ); After Munmap (2) is called, the in-memory data is written to the file, noting that the data written is only 5*sizeof (people) and not 10*sizeof (people) printf ("Umap OK \ n" ); return 0;}
#include <sys/mman.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>#include<stdio.h>typedefstruct{ Charname[4]; intAge ;} People;intMainintargcChar* * argv)//Map a normal file as shared mem:{ intFd,i; People*P_map; FD=open (argv[1], o_creat| O_RDWR,0777 ); P_map= (people*) mmap (NULL,sizeof(People) *Ten, prot_read|Prot_write, MAP_SHARED,FD,0); Close (FD); for(i =0;i<Ten; i++) {printf ("Name:%s Age%d;\n", (* (P_map+i)). Name, (* (p_map+i)). Age); } munmap (P_map,sizeof(People) *Ten );
Close (FD); return 0;}
Linux mmap system calls