在搜索引擎这些应用中,一个进程会把大量的索引数据写入到内存中,另一个进程来读内存。这个场景会使用共享内存。
共享内存和普通内存的区别
普通内存也可以用来共享数据,承担和共享内存一样的角色,为什么一定要使用共享内容呢。这个问题比较复杂,详细讨论可以参考文末链接。
示例
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 64
extern int errno;
int main()
{
int shmid;
char* shmptr;
// 创建共享内存
if ((shmid = shmget(IPC_PRIVATE, SIZE, 0600)) < 0)
{
printf("shmget error:%s\n", strerror(errno));
return -1;
}
printf("shmget sucess, shmid:%d\n", shmid);
// 将共享内存连接到可用地址上
if ((shmptr=(char*)shmat(shmid, 0, 0)) == (void*)-1)
{
printf("shmat error:%s\n", strerror(errno));
return -1;
}
memcpy(shmptr, "Hello Tencent", sizeof("Hello Tencent"));
printf("share memory from %lx to %lx, content:%s\n", \
(unsigned long)shmptr, (unsigned long)(shmptr + SIZE), shmptr);
if (shmctl(shmid, IPC_RMID, 0) < 0)
{
printf("shmctrl error:%s\n", strerror(errno));
return -1;
}
}
打印出
shmget sucess, shmid:1114122
share memory from 7f81eccf8000 to 7f81eccf8040, content:Hello Tencent
```
查看系统分配的共享内存 `ipcs`
```
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00005feb 0 root 666 12000 4
0x00005fe7 32769 root 666 524288 2
0x00005fe8 65538 root 666 2097152 3
0x00034036 98307 root 777 2072 1
0x048f233e 131076 x 666 268435456 1
0x048f233f 163845 xi 666 8388608 1
0x00212346 196614 titus 666 34079016 0
0xab9145cd 229383 titus 666 268436272 0
0x3a934f2b 262152 he 666 512 0
0x115fd81a 983049 root 666 4096 7
0x00000000 1114122 titus 600 64 0
------ Semaphore Arrays --------
key semid owner perms nsems
0x00008708 32769 root 666 1
0x000086f8 65538 root 666 1
0x0000870a 98307 root 666 1
0x00008707 131076 root 666 1
0x00008709 163845 root 666 1
0x00008706 196614 root 666 1
0x00034035 229383 root 777 1
0x00034048 262152 root 777 1
0x00034049 294921 root 777 1
0x00034034 327690 root 777 1
0x0000870d 360459 root 666 1
```
可以看到 shmid 为 1114122 的共享内存是我创建的。
## 参考
[http://blog.chinaunix.net/uid-26335251-id-3493125.html](http://blog.chinaunix.net/uid-26335251-id-3493125.html)
[https://www.zhihu.com/question/29973022/answer/85241481](https://www.zhihu.com/question/29973022/answer/85241481)