編程步驟:編程
1.建立共享內存,獲得一個共享內存ID(該ID通常大於50000)spa
2.把ID映射到虛擬地址(也稱爲「掛載」)code
3.操做共享內存blog
4.卸載虛擬地址進程
5.刪除共享內存ip
應用案例:內存
創建2個進程 A 和B 。其中A,建立共享內存,而且修改內存數據。get
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/shm.h> #include <sys/ipc.h> key_t key; int shmid; int *p; int i=0; void deal(int s) { if(s==SIGINT) { //4.卸載共享內存shmdt shmdt(p); //5.刪除共享內存shctl shmctl(shmid,IPC_RMID,0); exit(0); } } main() { signal(SIGINT,deal); //1.建立共享內存shmget key=ftok(".",255); if(key==-1) printf("ftok error:%m\n"),exit(-1); shmid=shmget(key,4,IPC_CREAT|IPC_EXCL|0666); if(shmid==-1) printf("get error:%m\n"),exit(-1); //2.掛載共享內存shmat p=shmat(shmid,0,0); if(p==(int*)-1) printf("at error:%m\n"),exit(-1); //3.訪問共享內存 while(1) { *p=i; sleep(1); i++; } }
B。根據ID獲得共享內存,而且訪問內存數據。string
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/shm.h> #include <sys/ipc.h> key_t key; int shmid; int *p; void deal(int s) { if(s==2) { //4.卸載共享內存shmdt shmdt(p); exit(0); } } main() { signal(SIGINT,deal); //1.建立共享內存shmget key=ftok(".",255); if(key==-1) printf("ftok error:%m\n"),exit(-1); shmid=shmget(key,4,0); if(shmid==-1) printf("get error:%m\n"),exit(-1); //2.掛載共享內存shmat p=shmat(shmid,0,0); if(p==(int*)-1) printf("at error:%m\n"),exit(-1); //3.訪問共享內存 while(1) { sleep(1); printf("%d\n",*p); } }