How do I use shared memory and memory-mapped IPC?

Shared memory provides a way for processes to communicate by accessing a common memory space. In C++, you can use the POSIX shared memory API or System V IPC to implement shared memory functionality. Memory-mapped IPC, on the other hand, allows a file to be mapped into the address space of a process, enabling inter-process communication through that file.

Below is a simple example demonstrating how to use shared memory and memory-mapped IPC in C++.

#include #include #include #include #include int main() { const char *key_path = "/shm_example"; const int shm_size = 1024; // Create shared memory segment int shm_id = shmget(ftok(key_path, 65), shm_size, 0666 | IPC_CREAT); char *shm_ptr = (char*) shmat(shm_id, nullptr, 0); // Write to shared memory std::string message = "Hello from shared memory!"; strncpy(shm_ptr, message.c_str(), shm_size); std::cout << "Written to shared memory: " << shm_ptr << std::endl; // Detach from shared memory shmdt(shm_ptr); // Optionally, remove shared memory segment (for cleanup) shmctl(shm_id, IPC_RMID, nullptr); return 0; }

shared memory memory-mapped IPC inter-process communication C++ IPC POSIX shared memory System V IPC