标签:getch mat code == nbsp memory pre hello memcpy
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
标签:getch mat code == nbsp memory pre hello memcpy
原文地址:https://www.cnblogs.com/lanmufan/p/14218611.html