共享内存图示说明:
实现机制:
共享内存时通过把一块内存分别映射到不同的进程空间中实现进程间通信。而共享内存本身不带任何互斥与同步机制,但当多个进程同时对同一个内存进行读写操作时会破坏该内存的内容。所以,在实际中,同步与互斥机制需要用户来完成。
头文件:
#include<sys/shm.h>
#include<sys/ipc.h>
创建或打开共享内存:
shmget(key_t key,size_t size);
size共享内存段的大小
flag 如果是创建填IPC_CREAT|0644,如果是打开填写0
nattch表示有几个进程映射到这块共享内存上
具体代码:
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<sys/ipc.h>
4 #include<sys/shm.h>
5 struct stu{
6 int id;
7 char name[20];
8 };
9 int main()
10 {
11 int shmid=shmget(1234,sizeof(struct stu),IPC_CREAT|0644);
12 if(shmid==-1)
13 {
14 perror("shmget");
15 exit(1);
16 }
17 printf("shmid:%d",shmid);
18 }
让共享内存和本进程建立关系:
shmat(int id ,const char*shmaddr,int flag)
id:已经打开的共享内存的id
shmaddr:想挂载到哪一块虚拟地址空间,填NULL,默认让操作系统选择一块空白的虚拟地址
flag:0
返回值:实际挂载到的虚拟地址的起始位置
卸载掉共享内存
shmdt(void *shmadr);
返回值为int 判断卸载成功与否
dt仅仅是让该进程与共享内存不再建立关系,但不是删除共享内存
具体代码:
1 #include<sys/shm.h>
2 #include<sys/ipc.h>
3 #include<stdlib.h>
4 #include<stdio.h>
5 #include<assert.h>
6 #include<string.h>
7 struct stu{
8 int id;
9 char name[20];
10 };
11 int main()
12 {
13 int shmid=shmget(1234,sizeof(struct stu),0);
14 if(shmid==-1)
15 {
16 perror("shmget");
17 exit(1);
18 }
19 struct stu *p=(struct stu *)shmat(shmid,NULL,0);
20 if(p==NULL)
21 {
22 return;
23 }
24 p->id=1;
25 strcpy(p->name,"mazhuzhu");
26 sleep(5);
27 shmdt(p);
28
29 }
删除共享内存
ipcrm -M key
int shmctl (int id,int cmd,NULL)
cmd:IPC_RMID 删除共享内存的指令
1 #include<sys/ipc.h>
2 #include<sys/shm.h>
3 #include<stdlib.h>
4 #include<stdio.h>
5 int main()
6 {
7 int id=shmget(1234,0,0);
8 shmctl(id,IPC_RMID,NULL);
9 }