Consider I have this kind of class in process 1. And run process2 whose code is written in completely different file.
class A{
public:
int data;
A()
int f();
}
I want to make instance a of class A in process1, send it to process2, and run a.f() in process2. I studied about IPC mechanism including POSIX shared memory or message queue and read many examples, but the most of examples only expalin how to send single data like integer, or struct without member function.
- Is it possible?
- If it's possible, how can I do it using POSIX shared memory? Can you give me short example?
It is definitely possible to do it in shared memory.
Take for example the following class:
The class uses an atomic counter inside that will be shared between two processes, both reading and writing from it.
Let's first create some shared memory space for it.
Notice I am not checking the return values for brevity but you should do in your code.
Now with this memory space allocated, let's initialize an object of class "A" inside that memory with placement new.
Then we fork another process to simulate the IPC mechanism working
For the parent process code, we loop from 0 to 10 first waiting for it to be different from zero then 2, 4 etc. Then in the end we wait for the child to finish.
For the child process, we write 1 and wait for 1, then write 3 and wait for 3 and so on like the parent but with odd numbers.
In the end of both we unmap the memory and close the file
It prints:
Compiler Explorer link: https://godbolt.org/z/5orPaEhPM
If you need two independent processes running side by side you just need to be careful with how you create them, synchronize them.
Start the same way opening a file and memory mapping it
Notice that at this point if you write or read from the pointer
ptryou will get a segfault.Then you need to lock the file
Then you need to check the file. If the size is zero, it is uninitialized. If the file is already initialized, you do not use placement new, you just cast the raw pointer.
After that you read your value and increment it while the file is still locked.
Then you can unlock the file
Then it's just the same drill of waiting, incrementing and looping, only a tad different.
In the end, just unmap and close as before
The whole code is here: https://godbolt.org/z/zK3WKWqj4