一,建立共用記憶體
void *shmat(int shmid, void *shmaddr, int shmflg);該系統調用將shmid 對應的共用記憶體區映射到進程的虛擬位址空間中,shmaddr 為指定的映射起始地址,其值為NULL 時,映射空間由系統確定;shmflg 為標誌字,其值一般指定為0。
/* * mkshm.c - Create and initialize shared memory segment */#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#define BUFSZ 4096 /* Size of the segment */int main(void){ int shmid; if((shmid = shmget(IPC_PRIVATE, BUFSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(EXIT_FAILURE); } printf("segment created: %d\n", shmid); system("ipcs -m"); exit(EXIT_SUCCESS);}
查看目前已有的共用記憶體命令:ipcs -m
二,向共用記憶體中寫入資料
/* * wrshm.c - Write data to a shared memory segment */#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <ctype.h>#include <unistd.h>#define BUFSZ 4096int main(int argc, char *argv[]){ int shmid;/* Segment ID */ char *shmbuf;/* Address in process */ key_t key; char *msg; int len; key = ftok("/tmp", 0); if((shmid = shmget(key, BUFSZ, IPC_CREAT|0666)) < 0) { perror("shmget"); exit(EXIT_FAILURE); } printf("segment created: %d\n", shmid); system("ipcs -m"); /* Attach the segment */ if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) { perror("shmat"); exit(EXIT_FAILURE); } /* Write message to the segment */ msg = "this is the message written by wrshm program."; len = strlen(msg); strcpy(shmbuf, msg); printf("%s\nTotal %d characters written to shared memory.\n", msg, len); /* De-attach the segment */ if(shmdt(shmbuf) < 0) { perror("shmdt"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS);}
三,從共用記憶體中讀入資料
/* * wrshm.c - Write data to a shared memory segment */#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <ctype.h>#include <unistd.h>#define BUFSZ 4096int main(int argc, char *argv[]){ int shmid;/* Segment ID */ char *shmbuf;/* Address in process */ key_t key; int len; key = ftok("/tmp", 0); /* get the same share memory block */ if((shmid = shmget(key, 0, 0)) < 0) { perror("shmget"); exit(EXIT_FAILURE); } /* Attach the segment */ if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) { perror("shmat"); exit(EXIT_FAILURE); } /* read from share memory */ printf("Info read form shared memory is:\n%s\n", shmbuf); /* De-attach the segment */ if(shmdt(shmbuf) < 0) { perror("shmdt"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS);}