共享內(nèi)存通信方式效率最高,,畢竟是直接操作內(nèi)存,,但是要保證多個(gè)進(jìn)程對(duì)同一塊內(nèi)存訪問(wèn)的同步互斥比較麻煩,,借助信號(hào)量實(shí)現(xiàn)
對(duì)每個(gè)共享存儲(chǔ)段,,內(nèi)核維護(hù)一個(gè)shmid_ds類型的結(jié)構(gòu)體,定義在<sys/shm.h>文件中
- struct shmid_ds
- {
- struct ipc_perm shm_perm; //共享內(nèi)存的ipc_perm結(jié)構(gòu)
- size_t shm_segsz; //共享內(nèi)存區(qū)域大小,,字節(jié)表示
- pid_t shm_lpid; //最后一次調(diào)用shmop函數(shù)的進(jìn)程ID
- pid_t shm_cpid; //創(chuàng)建此共享內(nèi)存的進(jìn)程ID
- unsigned short shm_lkcnt; //共享內(nèi)存被鎖定的時(shí)間數(shù)
- unsigned long shm_nattch; //當(dāng)前使用共享內(nèi)存的進(jìn)程數(shù)
- time_t shm_atime; //最后一次附加操作時(shí)間
- time_t shm_dtime; //最后一次分離操作時(shí)間
- time_t shm_ctime; //最后一次修改時(shí)間
- }
共享內(nèi)存基本操作
1,,創(chuàng)建或打開(kāi)一個(gè)共享內(nèi)存(shmget)
- //create_shm.c
- #include<sys/types.h>
- #include<sys/ipc.h>
- #include<sys/shm.h>
- #include<stdio.h>
-
- #define BUFSZ 1024
-
- int main()
- {
- int shm_id; //共享內(nèi)存ID
- shm_id = shmget(IPC_PRIVATE,BUFSZ,0666);
- if(shm_id < 0){
- printf("shmget failed\n");
- return -1;
- }
- printf("create shared memory succeed: %d\n",shm_id);
- system("ipcs -m"); //查看共享內(nèi)存ID
- return 0;
- }
2,附加共享內(nèi)存到進(jìn)程空間(shmat/shmdt)
- //attach_shm.c
- #include<sys/types.h>
- #include<sys/ipc.h>
- #include<sys/shm.h>
- #include<stdio.h>
-
- #define BUFSZ 1024
-
- int main()
- {
- int *shm;
- shm = shmat(104529925,NULL,0);
- if(*shm == -1){
- printf("shmat failed\n");
- return -1;
- }
- printf("attach shared memory succeed: %d\n",*shm);
- system("ipcs -m"); //查看共享內(nèi)存調(diào)用狀態(tài)
- if(shmdt(shm) == -1){
- printf("shmdt failed\n");
- return -1;
- }
- system("ipcs -m"); //查看共享內(nèi)存調(diào)用狀態(tài)
- return 0;
- }
3,共享內(nèi)存控制函數(shù)(shmctl)
下面寫個(gè)簡(jiǎn)單的例子
共享內(nèi)存寫端(write_shm.c)
- //write_shm.c
- #include<sys/types.h>
- #include<sys/ipc.h>
- #include<sys/shm.h>
- #include<stdio.h>
-
- typedef struct
- {
- char name[4];
- int age;
- }people;
-
- int main()
- {
- int i;
- char *t = 'a';
- people *p_shm = NULL;
- p_shm = shmat(104529925,NULL,0);
- if(p_shm == NULL){
- printf("shmat failed\n");
- return -1;
- }
- for(i=0;i<5;i++) {
- t += 1;
- memcpy((*(p_shm+i)).name,&t,1);
- (*(p_shm+i)).age = 20+i;
- }
- if(shmdt(p_shm) == -1){
- printf("shmdt failed\n");
- return -1;
- }
- return 0;
- }
共享內(nèi)存讀端(read_shm.c)
- //read_shm.c
- #include<sys/types.h>
- #include<sys/ipc.h>
- #include<sys/shm.h>
- #include<stdio.h>
-
- typedef struct
- {
- char name[4];
- int age;
- }people;
-
- int main()
- {
- int i;
- char *t = 'a';
- people *p_shm = NULL;
- p_shm = shmat(104529925,NULL,0);
- if(p_shm == NULL){
- printf("shmat failed\n");
- return -1;
- }
- for(i=0;i<5;i++) {
- printf("name:%s age:%d\n",(*(p_shm+i)).name,(*(p_shm+i)).age);
- }
- if(shmdt(p_shm) == -1){
- printf("shmdt failed\n");
- return -1;
- }
- return 0;
- }
先后編譯執(zhí)行"寫代碼"與"讀代碼",結(jié)果如下
- root$ ./write_shm.out
- root$ ./read_shm.out
- name:b age:20
- name:c age:21
- name:d age:22
- name:e age:23
- name:f age:24
|