程式語言 - GNU - C/C++ - Share Memory(mmap)



參考資訊:
https://stackoverflow.com/questions/22721209/sharing-memory-between-processes-on-linux

server.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>

#define SHM_NAME     "SHM"
#define SHM_BUF_SIZE 4096

int main(int argc, char *argv[])
{
    int fd = -1;
    char *buf = NULL;

    fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0777);
    ftruncate(fd, SHM_BUF_SIZE);
    buf = mmap(NULL, SHM_BUF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    buf[0] = 0;

    usleep(3000000);
    printf("%s\n", buf);

    munmap(buf, SHM_BUF_SIZE);
    shm_unlink(SHM_NAME);

    return 0;
}

client.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>

#define SHM_NAME     "SHM"
#define SHM_BUF_SIZE 4096

int main(int argc, char *argv[])
{
    int fd = -1;
    char *buf = NULL;

    fd = shm_open(SHM_NAME, O_RDWR, 0777);
    buf = mmap(NULL, SHM_BUF_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);

    strcpy(buf, "I am error !");

    munmap(buf, SHM_BUF_SIZE);
    shm_unlink(SHM_NAME);

    return 0;
}

編譯、執行

$ gcc client.c -o client
$ gcc server.c -o server

$ ./server&
$ sleep 1
$ ./client
    I am error !