/******write.c******/ # 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; int shmdt_id; key_t key; char temp; people *p_map; char* name = "."; key = ftok(name,0); if (key == -1) { perror("ftok error"); return; } shm_id = shmget(key,4096,IPC_CREAT); //調(diào)用shmget創(chuàng)建一塊共享主存區(qū) if (shm_id == -1) { perror("shmget error"); return; } p_map = (people*)shmat(shm_id,NULL,0);//將共享主存區(qū)附加到自己的主存段 temp = 'a'; for (i = 0 ;i < 10 ; i++ ) //向共享主存中寫入數(shù)據(jù) { temp = temp + 1; memcpy((*(p_map + 1)).name,&temp,1); (*(p_map+i)).age = 20 + i; } shmdtid = shmdt(p_map); //將其從自己的主存段中“刪除”出去 if(shmdtid == -1) //刪除失敗 { perror("detach error"); return; } }
|