这篇文章主要讲解了“数据库内存共享实现原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“数据库内存共享实现原理是什么”吧!
共享内存是进程间通讯的一种方式,PostgreSQL使用共享内存缓存数据以及各种数据结构.
下面是演示代码,逻辑很简单,自行参考代码注释.
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//1k共享内存
#define SHM_SIZE 1024
#define SHM_ID 10086
int main()
{
//共享内存id,子进程id
int shmid, pid;
//共享内存指针
char *ptr = NULL;
//申请共享内存
shmid = shmget((key_t)SHM_ID, SHM_SIZE, IPC_CREAT | 0600);
//映射共享内存到进程地址空间
ptr = (char *)shmat(shmid, 0, 0);
printf("Attach pointer addr is %p \n", ptr);
ptr = "This is shared memory!";
printf("The String of Parent Process is : %s \n", ptr);
if((pid = fork()) == -1)
{
perror("fork process error!");
exit(0);
}
else if(!pid)
{
printf("Child Process PID is : %d,String is %s \n", pid,ptr);
exit(0);
}else{
sleep(1);
//解除映射
shmdt(ptr);
//删除共享内存
shmctl(shmid, IPC_RMID, 0);
}
return 0;
}
运行输出
[pg12@localhost ipc]$ gcc -std=c11 -o fork fork.c
In file included from fork.c:7:0:
/usr/include/sys/ipc.h:24:3: warning: #warning "Files using this header must be compiled with _SVID_SOURCE or _XOPEN_SOURCE" [-Wcpp]
# warning "Files using this header must be compiled with _SVID_SOURCE or _XOPEN_SOURCE"
^
[pg12@localhost ipc]$ ./fork
Attach pointer addr is 0x7f61ffb6b000
The String of Parent Process is : This is shared memory!
Child Process PID is : 0,String is This is shared memory!
[pg12@localhost ipc]$
感谢各位的阅读,以上就是“数据库内存共享实现原理是什么”的内容了,经过本文的学习后,相信大家对数据库内存共享实现原理是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!