Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared memory interprocess communication

I allocated a block of shared memory using shmget.

Then I attach the shared memory to process A and process B respectively using shmat. I assume the handles(i.e.,addresses within A and B that are mapped to the actual shared memory) for A and B returned by shmat are different.

Let's assume the handles for A and B are defined as char* p and char* q respectively. My question is if we write an object to the address p + sizeof(anotherObject) within process A, can we expect to get the same object at the address q + sizeof(anotherObject) within process B?

I guess it is the case but am not 100% sure. If so, how is this communication or mapping mechanism being achieved since we know that p + sizeof(anotherObject) and q + sizeof(anotherObject) are referring to different memory locations?

like image 202
Terry Li Avatar asked Apr 30 '26 18:04

Terry Li


1 Answers

Modern processors use virtual address spaces. The address, you're using in you program is not the "real" address of the objects, the operating system and the processor maps pages of memory to an address range, and you use that as "memory".

Creating a shared memory simply means that the OS maps the same memory page into two or more different processes' address spaces. The fact that the two pointers in the two processes do not have the same numeric value means nothing, even if pointers in different processes have the same numeric value, they usually point to different memory locations.

About writing the "object" to the memory, you first have to "serialize" it. I mentioned that pointers in different processes are incompatible with each other. If your object has any pointer members, or other objects that may contain pointers, you have to come up with a way to replace those pointers with the actual data, because once you read the object from the other thread, those pointers are as good as trash.

Be aware that C++ std::sting, std::vector and the other containers, along with any virtual object (object that have virtual function) have pointers inside them. so if you want to pass a string you need to write it as a sequence of characters into the shared memory, and read the same way on the other side.

like image 141
Evan Dark Avatar answered May 03 '26 06:05

Evan Dark