Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have two c++ programs access to the same memory location

Currently working on a project where I have to send the same data to two different places: One is over IP to a server, the other one is local. The idea is to store the data on a remote server and plot the data using QT on the local machine in real time.

My data (coming from microcontroller) is received using a c++ client through serial port; The client sends the data to a c++ server, but I need to plot the data using QT which is a different program independent of c++ client.

I am wondering if two different programs can access to the same memory location just to read the data if I have the memory address of the data!

Here is what I already have: 1. My client program is able to store the data memory address to a txt file. 2. Now I'm testing to manually hard code the memory address to see if I can get the same data.

The problem is that my testing code doesn't output anything. It ran and stopped without doing anything. Here is my testing code:

char* ptr_rx = (char *)0x7fffd2848df0;
cout << ptr_rx << endl;

My client is running when I tried to use another program to read the data using the memory address, so its address should remain the same as long as the client is running.

Please let me know if it's even possible to access the same memory location using memory address by two different programs. I will call it off if it's not possible.

like image 650
Hong Pan Avatar asked Dec 26 '22 03:12

Hong Pan


1 Answers

You can't simply use an absolute address like that, because on modern OSes with virtual memory, each process has their own memory map. You need to use an API to share memory.

If on Linux or other UNIX flavor, you can use shared memory segments. The low level method is the POSIX API. Other APIs (Qt, Boost) have wrappers that ultimately use this.

With shmget you define a unique identifier. You will use that key for your processes to identify the same segment of memory.

The first process to call shmget() causes an allocation, and subsequent processes which call it will receive a "reference" to it. Both processes need to attach to it with shmat() in order to work with a pointer.

Good examples here: http://www.cs.cf.ac.uk/Dave/C/node27.html

Another sample on Stack Overflow: How to use shared memory with Linux in C

Obviously, the processes will need to have an identifier (token) to identify the unique shared memory segment.

First process will allocate the memory, second will attach (shmget will return either a new segment, or existing segment):

int key = 12345;
int shmid;

if ((shmid = shmget (key, 4096, IPC_CREAT)) == -1) {
    perror("shmget: ");
    exit(1);
}

cerr << "Shared segment allocated shmid " << shmid << endl;

// attach
char *shmbuf = shmat(shmid, NULL);
like image 83
codenheim Avatar answered Dec 27 '22 18:12

codenheim