进程间通信-IPC题稿.ppt
文本预览下载声明
读共享内存 示例一 #include sys/types.h #include sys/ipc.h #include sys/shm.h #include stdio.h #include error.h #include stdlib.h #define SHM_SIZE 4096 #define SHM_MODE (SHM_R | SHM_W | IPC_CREAT) /* user read/write */ int main(void) { int shmid; char *shmptr; if ( (shmid = shmget(0x44, SHM_SIZE, SHM_MODE)) 0) perror(shmget); if ( (shmptr = shmat(shmid, 0, 0)) == (void *) -1) perror(shmat); printf(%s\n, shmptr); /* 从共享内存读数据 */ exit(0); } 写共享内存 示例二 #include sys/ipc.h #include sys/shm.h #include sys/types.h #include unistd.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 = /usr/local/2013_autumn; key = ftok(name,0); if(key==-1) perror(ftok error); shm_id=shmget(key,4096,IPC_CREAT); if(shm_id==-1){ perror(shmget error); return; } printf(sharemem id is:%d\n,shm_id); p_map=(people*)shmat(shm_id,NULL,0); temp=a; for(i = 0;i10;i++){ memcpy((*(p_map+i)).name,temp,1); (*(p_map+i)).age=20+i; temp+=1; } if(shmdt(p_map)==-1) perror( detach error ); return 0; } 读共享内存示例二 #include sys/ipc.h #include sys/shm.h #include sys/types.h #include unistd.h typedef struct{ char name[4]; int age; } people; main(int argc, char** argv) { int shm_id, i; key_t key; people *p_map; char* name = /usr/local/2013_autumn; key = ftok(name,0); if(key == -1) perror(ftok error); shm_id = shmget(key,4096,IPC_CREAT); if(shm_id == -1) { perror(shmget error); return; } p_map = (people*)shmat(shm_id,NULL,0); for(i = 0;i10;i++)
显示全部