数据库实现原理#6(共享内存)

共享内存是进程间通讯的一种方式,PostgreSQL使用共享内存缓存数据以及各种数据结构.
下面是演示代码,逻辑很简单,自行参考代码注释.


/*
申请一段共享内存,父进程写入一串字符,子进程读出。
*/
#include 
#include 
#include 
#include 
#include 
#include 
//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]$
请使用浏览器的分享功能分享到微信等