共享内存:在其物理内存上创建出一块内存区,然后将两个或多个进程挂接到这块内存上,这样这块内存区就是这两个进程共享的了。此后,在任何一个进程内进行操作,另一个进程也可见。当不再需要这块共享资源时,再将进程分别与该内存区断开。
共享内存是进程间通信最高效的方式,因为它省去了将数据拷贝到内核,再从内核拷贝出去的时间。
但共享内存需要自己维护同步与互斥。
函数:
int shmget(key_t key,size_t size,int shmflg);
int shmctl(int shmid,int cmd,struct shm *buf);
void *shmat(int shmid,const void *shmaddr,int shmflg);
int shmdt(const void* shmaddr);
comm.h
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<sys/types.h>
5 #include<sys/ipc.h>
6 #include<sys/shm.h>
7
8 #define _PATH_ "."
9 #define _PROJ_ID_ 0x6666
10 #define _SIZE_ 4096
11
12 int creat_shm();
13 int get_shm();
14 void *at_shm(int shm_id);
15 int dt_shm(char* arr);
16 int destroy_shm(int shm_id);
comm.c
1 #include"comm.h"
2
3 static int comm_creat_shm(int flags)
4 {
5 key_t _key = ftok(_PATH_,_PROJ_ID_);
6 if(_key == -1)
7 {
8 perror("ftok");
9 return -1;
10 }
11 int shm_id = shmget(_key,_SIZE_,flags);
12 if(shm_id ==-1)
13 {
14 perror("shmget");
15 return -1;
16 }
17 return shm_id;
18
19 }
20 int creat_shm()
21 {
22 int flags = IPC_CREAT|IPC_EXCL|0666;
23 return comm_creat_shm(flags);
24 }
25 int get_shm()
26 {
27 int flags = IPC_CREAT;
28 return comm_creat_shm(flags);
29
30 }
31 void *at_shm(int shm_id)
32 {
33 return (char*)shmat(shm_id,NULL,0);
34 }
35 int dt_shm(char* arr)
36 {
37 if(shmdt(arr)==-1)
38 {
39 perror("shmdt");
40 return -1;
41 }
42 return 0;
43 }
44 int destroy_shm(int shm_id)
45 {
46 if(shmctl(shm_id,IPC_RMID,NULL)==-1)
47 {
48 perror("shmctl");
49 return -1;
50 }
51 return 0;
52 }
server.c
1 #include"comm.h"
2
3 int main()
4 {
5 int shm_id = creat_shm();
6 char *arr = at_shm(shm_id);
7 sleep(10);
8 dt_shm(arr);
9 sleep(10);
10 destroy_shm(shm_id);
11 return 0;
12 }
client.c
1 #include"comm.h"
2 int main()
3 {
4 int shm_id = get_shm();
5 char *arr = at_shm(shm_id);
6 sleep(5);
7 dt_shm(arr);
8 sleep(7);
9 return 0;
10 }原文:http://fengbaoli.blog.51cto.com/10538178/1763882