1

Having done research, there isn't a good stack overflow post on how to share memory between two separate applications in C++, that comes with code.

One solution can be found here: How to use shared memory with Linux in C

But it requires a process to be forked so that memory mmap's to the same location. It doesn't work for two separate applications.

Whats the most efficient way to write two applications that share data using a memory space?

Mich
  • 3,188
  • 4
  • 37
  • 85
  • Standard C++ has no support for memory mapping, and this looks like C code. And we don't have to explain downvotes. –  Mar 14 '19 at 19:31
  • 4
    I personally downvoted this question, because I do not think it is well researched, or well presented question. I do not understand what OP is asking. "How to map shared memory using `mmap`"? Such question doesn't need the code for the client and the server, it is a straightforward question, which can yield an answer in 1 second if exactly this phrase is typed into google. Or did OP try some code with mmap and failed in those attempts? Than what code did OP try, and how did they fail? – SergeyA Mar 14 '19 at 19:45
  • @Mich Have you look at boost IPC ? https://www.boost.org/doc/libs/1_63_0/doc/html/interprocess/sharedmemorybetweenprocesses.html – Vuwox Mar 14 '19 at 19:46

1 Answers1

4

This is my solution using shmget, its outdated, but it works

Host:

#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    char output[] = "test";
    int shmid=shmget(IPC_PRIVATE, sizeof(output), 0666);
    FILE *fp;
    fp = fopen("/tmp/shmid.txt", "w+");
    fprintf(fp, "%d", shmid);
    fclose(fp);
    int *mem_arr;

    while(true)
    {
        mem_arr = (int *)shmat(shmid, NULL, 0);
        memcpy(mem_arr, output, sizeof(output));
        shmdt(mem_arr);
    }
    return 1;
}

Client:

#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    char output[] = "test";
    FILE *fp;
    fp = fopen("/tmp/shmid.txt", "r");
    int shmid;
    fscanf (fp, "%d", &shmid);  
    fprintf(fp, "%d", shmid);
    fclose(fp);

    while(true)
    {
        int* shared_mem = (int *)shmat(shmid, NULL, 0);
        printf("data: %s\n", shared_mem);
    }
    return 1;
}
Mich
  • 3,188
  • 4
  • 37
  • 85