写程序
- #include"sys/ipc.h"
- #include"sys/shm.h"
- #include"sys/types.h"
- #include"unistd.h"
- #include"stdio.h"
- #include"string.h"
- typedef struct{
- char name[4];
- int age;
- }people;
- main(int argc,char** argv)
- {
- int shm_id,i;
- key_t key;
- char temp;
- people *p_map;
- char* name="..";
- key=ftok(name,0);
- if(key==-1)
- perror("ftok error!");
- shm_id=shmget(key,4096,IPC_CREAT|0666);
- if(shm_id==-1)
- {
- perror("shmget error!");
- return;
- }
- p_map=(people*)shmat(shm_id,NULL,0);
- temp='a';
- for(i=0;i<10;i++)
- {
- temp++;
- memcpy((*(p_map+i)).name,&temp,1);
- (*(p_map+i)).age=20+i;
- }
- if(shmdt(p_map)==-1)
- perror("detach error!");
- }
读程序
- #include"sys/ipc.h"
- #include"sys/shm.h"
- #include"sys/types.h"
- #include"unistd.h"
- #include"stdio.h"
- typedef struct{
- char name[4];
- int age;
- }people;
- main(int argc,char** argv)
- {
- int shm_id,i;
- key_t key;
- //char temp;
- people *p_map;
- char* name="..";
- key=ftok(name,0);
- if(key==-1)
- perror("ftok error!");
- shm_id=shmget(key,4096,IPC_CREAT|0666);
- if(shm_id==-1)
- {
- perror("shmget error!");
- return;
- }
- p_map=(people*)shmat(shm_id,NULL,0);
- //temp='a';
- for(i=0;i<10;i++)
- {
- printf("name:%s ",(*(p_map+i)).name);
- printf("age %d ",(*(p_map+i)).age);
- }
- if(shmdt(p_map)==-1)
- perror("detach error!");
- }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/732489