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 do14 {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!\n"); 53 munmap(p,sizeof(STU)*5); 54 printf("exit....\n"); 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 do14 {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\n",(p+i)->name,(p+i)->age); 48 } 49 munmap(p,sizeof(STU)*5); 50 printf("exit....\n"); 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);
原文:https://www.cnblogs.com/zhaohu/p/8998649.html