天天看点

Linux 共享内存 例程 C/C++ 自学笔记

/写内存/

#include <stdio.h>

#include <sys/shm.h>

#include <string.h>

int main()

{

    // 1. 创建共享内存, 大小为4k

    int shmid = shmget(1000, 4096, IPC_CREAT|0664);

    if(shmid == -1)

    {

        perror("shmget error");

        return -1;

    }

    // 2. 当前进程和共享内存关联

    void* ptr = shmat(shmid, NULL, 0);

    if(ptr == (void *) -1)

    {

        perror("shmat error");

        return -1;

    }

    // 3. 写共享内存

    const char* p = "hello, world, 共享内存真香/...";

    memcpy(ptr, p, strlen(p)+1);

    // 阻塞程序

    printf("按任意键继续, 删除共享内存\n");

    getchar();

    shmdt(ptr);

    // 删除共享内存

    shmctl(shmid, IPC_RMID, NULL);

    printf("共享内存已经被删除...\n");

    return 0;

}

/读内存/

#include <stdio.h>

#include <sys/shm.h>

#include <string.h>

int main()

{

    // 1. 创建共享内存, 大小为4k

    int shmid = shmget(1000, 0, 0);

    if(shmid == -1)

    {

        perror("shmget error");

        return -1;

    }

    // 2. 当前进程和共享内存关联

    void* ptr = shmat(shmid, NULL, 0);

    if(ptr == (void *) -1)

    {

        perror("shmat error");

        return -1;

    }

    // 3. 读共享内存

    printf("共享内存数据: %s\n", (char*)ptr);

    // 阻塞程序

    printf("按任意键继续, 删除共享内存\n");

    getchar();

    shmdt(ptr);

    // 删除共享内存

    shmctl(shmid, IPC_RMID, NULL);

    printf("共享内存已经被删除...\n");

    return 0;

}

注:

1.以上内容转载自:https://subingwen.cn/linux/shm/#4-%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1 爱编程的大丙

继续阅读