标签:shmget demo memory share SHM printf shmid include ptr
shm.h
1 #ifndef __SHM_H 2 #define __SHM_H 3 4 #include <stdio.h> 5 6 #include <sys/ipc.h> 7 #include <sys/shm.h> 8 9 #define SHM_KEY ((key_t)0x20201231) 10 #define SHM_SIZE (16 * 1024 * 1024) 11 12 #endif//__SHM_H
shm_A.c
1 #include "shm.h" 2 3 #include <string.h> 4 5 6 int main(void) 7 { 8 int shmid = shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0664); 9 if(-1 == shmid) 10 { 11 printf("shmget fail\n"); 12 return -1; 13 } 14 else 15 { 16 printf("shmget ok,shmid = %d\n",shmid); 17 } 18 19 void* ptr = shmat(shmid,NULL,0); 20 if(((void*)-1) == ptr) 21 { 22 printf("shmat fail\n"); 23 return -1; 24 } 25 else 26 { 27 printf("shmat ok,ptr = %p\n",ptr); 28 } 29 30 char tmpString[] = "hello ipc shm!"; 31 memcpy(ptr,tmpString,sizeof(tmpString)); 32 33 getchar(); 34 35 return 0; 36 }
shm_B.c
1 #include "shm.h" 2 3 int main(void) 4 { 5 int shmid = shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0664); 6 if(-1 == shmid) 7 { 8 printf("shmget fail\n"); 9 return -1; 10 } 11 else 12 { 13 printf("shmget ok,shmid = %d\n",shmid); 14 } 15 16 void* ptr = shmat(shmid,NULL,0); 17 if(((void*)-1) == ptr) 18 { 19 printf("shmat fail\n"); 20 return -1; 21 } 22 else 23 { 24 printf("shmat ok,ptr = %p\n",ptr); 25 } 26 27 printf("%s\n",(char*)ptr); 28 29 getchar(); 30 31 return 0; 32 }
1.the 1st var of shmget can be get from ftok
2.you can check the share memory status by cmd
ipcs -m
3.you can delete the share memory by cmd
ipcrm -M key
or ipcrm -m shmid
标签:shmget,demo,memory,share,SHM,printf,shmid,include,ptr 来源: https://www.cnblogs.com/lanmufan/p/14218611.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。