结构体定义文件
#include <iostream>
#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
struct SharedData {
int id;
char name[100];
};
进程一
int main() {
const char* shm_name = "MySharedMemory";
const int SIZE = sizeof(SharedData);
int shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
return 1;
}
// Set the size of the shared memory object
ftruncate(shm_fd, SIZE);
// Memory map the shared memory object
void* ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
return 1;
}
// Create and write the structure to shared memory
SharedData* data = new(ptr) SharedData; // Placement new
data->id = 1;
strcpy(data->name, "SharedMemoryExample");
std::cout << "Data written to shared memory: " << data->id << ", " << data->name << std::endl;
// Unmap and close are typically done in a cleaner way or in another part of the program
munmap(ptr, SIZE);
close(shm_fd);
return 0;
}
进程二
int main() {
const char* shm_name = "MySharedMemory";
const int SIZE = sizeof(SharedData);
int shm_fd = shm_open(shm_name, O_RDONLY, 0666);
if (shm_fd == -1) {
perror("shm_open");
return 1;
}
// Memory map the shared memory object
void* ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
return 1;
}
// Read the structure from shared memory
SharedData* data = (SharedData*) ptr;
std::cout << "Read from shared memory: ID = " << data->id << ", Name = " << data->name << std::endl;
// Cleanup
munmap(ptr, SIZE);
close(shm_fd);
return 0;
}