- void *mmap(void *addr,size_t len,int prot,int flags, int fd,off_t offset);
- prot:保护方式
- PROT_READ:页面可读
- PROT_WRITE:页面可写
- PROT_EXEC:
- PROT_NONE:
- fiags:
- MAP_SHARED:
- MAP_PRIVATE:变动是私有的
- MAP_FIXED:准确解释addr
- MAP_ANONYMOUS:建立匿名映射去,不涉及文件
- mmap是以页面为单位来反配内存,内存是页面的整数倍
- int munmmap(int fd,size_t size)
- int msync(void *addr, size_t len,int flags)
- flags:
- MS_ANYNC:执行异步写
- MS_SYNC:执行同步写
- MS_INVALIDATR:是高速缓存失效
- flags:
- 注意
- 映射不能改变文件的大小
- 举个栗子
-
1 //创建共享内存 2 #include <sys/mman.h> 3 #include <unistd.h> 4 #include <sys/types.h> 5 6 #include <stdlib.h> 7 #include <stdio.h> 8 #include <errno.h> 9 #include <sys/stat.h> 10 #include <fcntl.h> 11 12 #define ERR_EXIT(m) 13 do 14 { 15 perror(m); 16 exit(EXIT_FAILURE); 17 }while(0) 18 19 typedef struct stt 20 { 21 char name[4]; 22 int age; 23 }STU; 24 25 int main(int argc,char *argv[]) 26 { 27 if(argc != 2) 28 { 29 exit(EXIT_FAILURE); 30 } 31 32 int fd; 33 fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 0666); 34 if(fd == -1) 35 { 36 ERR_EXIT("open"); 37 } 38 lseek(fd,sizeof(STU) * 5 -1,SEEK_SET); 39 write(fd,"",1); 40 STU *p; 41 p = (STU*)mmap(NULL,sizeof(STU)*5,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0); 42 if( p == NULL) 43 ERR_EXIT("mmap"); 44 char ch = 'a'; 45 int i; 46 for(i = 0;i< 5;i++) 47 { 48 memcpy((p+i)->name,&ch,1); 49 (p+i)->age= 20 + i; 50 ch++; 51 } 52 printf("Initlize over! "); 53 munmap(p,sizeof(STU)*5); 54 printf("exit.... "); 55 return 0; 56 }
-
1 //读取共享内存 2 #include <sys/mman.h> 3 #include <unistd.h> 4 #include <sys/types.h> 5 6 #include <stdlib.h> 7 #include <stdio.h> 8 #include <errno.h> 9 #include <sys/stat.h> 10 #include <fcntl.h> 11 12 #define ERR_EXIT(m) 13 do 14 { 15 perror(m); 16 exit(EXIT_FAILURE); 17 }while(0) 18 19 typedef struct stt 20 { 21 char name[4]; 22 int age; 23 }STU; 24 25 int main(int argc,char *argv[]) 26 { 27 if(argc != 2) 28 { 29 exit(EXIT_FAILURE); 30 } 31 32 int fd; 33 fd = open(argv[1], O_RDWR); 34 if(fd == -1) 35 { 36 ERR_EXIT("open"); 37 } 38 39 STU *p; 40 p = (STU*)mmap(NULL,sizeof(STU)*5,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0); 41 if( p == NULL) 42 ERR_EXIT("mmap"); 43 char ch = 'a'; 44 int i; 45 for(i = 0;i< 5;i++) 46 { 47 printf("name = %s, age = %d ",(p+i)->name,(p+i)->age); 48 } 49 munmap(p,sizeof(STU)*5); 50 printf("exit.... "); 51 return 0; 52 }
-
-
System V共享内存
- 随内核持续(同消息队列)
-
1 //共享内存函数 2 #include <sys/ipc.h> 3 #include <sys/shm.h> 4 5 //创建或者访问一个共享内存 6 int shmget(key_t key,size_t size,int shmflg); 7 //映射 8 void* shmat(int shmid,const void *shmaddr,int shmflg); 9 //脱离 10 int shmdt(const void *shmaddr); 11 //控制 12 int shmctl(int shimid,int cmd, struct shmid_ds *buf);