System V共享内存区实例转自:http://blog.chinaunix.net/u/21158/showart_226270.html使用共享内存的步骤还是相当简单的:1、获得唯一的key值,书上提到ftok不一定能得到唯一的键值;2、使用shmget创建或着获得共享内存区;3、使用shmat将共享内存区附加到进程中;4、使用共享内存区,。。。5、与共享内存区脱离,但是记住这时共享内存区依然存在,必须等到内核重启。6、申请的共享内存区的大小是有限制的。#############IPCShm1.cc#include #include #include #include #include #include #includetypedef struct{ char name[4]; int age;}people;int main(int argc, char *argv[]){ int shm_id,i; key_t key; char temp; people *p_map; char *path = "/home/program/mmapfile.cc"; /* 使用 ftok根据path和作为项目标识符的单个字符生成key值确保进程间使用相同的 key 使用相同key值的shmget只会在第一次时创建新结构,*/ key = ftok(path,0); if(key == -1) { perror("ftok error \n"); return -1; } shm_id = shmget(key,4096,IPC_CREAT); if(shm_id == -1) { perror("shmget error \n"); return -1; } p_map = (people*)shmat(shm_id,NULL,0); temp = 'a'; for(i = 0; i { temp +=1; memcpy((*(p_map+i)).name,&temp,1); (*(p_map+i)).age = 20+i; } system("ipcs -m"); if(shmdt(p_map) == -1) { perror("detach error"); } system("ipcs -m");}/* System V共享内存区是放在内核当中的,因此在内核重新引导之前,对数据的修改是一直保持的 ,这也是我们的实验能够实现的原因,因为在第二个进程起动时,第一个进程已经运行结束了.*/#########IPCShm2.cc#include #include #include #include #include/*完成从共享内存区的读出*/typedef struct{ char name[4]; int age; }people; int main (int argc, char** argv){ int shm_id, i; key_t key; people *p_map; char *path = "/home/program/mmapfile.cc"; key = ftok(path,0); if(key == -1) { perror("ftok error \n"); return -1; } shm_id = shmget(key,4096,IPC_CREAT); if(shm_id == -1) { perror("shmget error"); return -1; } p_map = (people*)shmat(shm_id,NULL,0); for(i=0; i { printf("name:%s\t",(*(p_map+i)).name); printf("age:%d\n",(*(p_map+i)).age); } system("ipcs -m"); if(shmdt(p_map) == -1) { perror("shmdt error\n"); return -1; } system("ipcs -m"); exit(EXIT_SUCCESS); } / 运行结果:name:b age:20name:c age:21name:d age:22name:e age:23name:f age:24name:g age:25name:h age:26name:i age:27name:j age:28name:k age:29 ------ Shared Memory Segments --------key shmid owner perms bytes nattch status0x00000001 32768 root 600 655360 20x00020069 262145 root 0 4096 1 ------ Shared Memory Segments --------key shmid owner perms bytes nattch status0x00000001 32768 root 600 655360 20x00020069 262145 root 0 4096 0 02-11 11:09