文章详情
linux进程共享内存【POSIX】
Posted on 2025-06-01 10:07:26 by 主打一个C++
主端
#include <iostream>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#define SHM_NAME "/my_shm"
#define SHM_SIZE 1024
int main() {
// 创建共享内存对象
int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
return 1;
}
// 调整共享内存对象的大小
if (ftruncate(shm_fd, SHM_SIZE) == -1) {
perror("ftruncate");
close(shm_fd);
return 1;
}
// 将共享内存对象映射到进程的地址空间
void* ptr = mmap(0, SHM_SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
return 1;
}
// 写入数据到共享内存
const char* message = "Hello, this is a shared memory example!";
std::memcpy(ptr, message, strlen(message) + 1);
// 等待一段时间,以便reader进程可以读取数据
sleep(5);
// 取消映射共享内存
if (munmap(ptr, SHM_SIZE) == -1) {
perror("munmap");
close(shm_fd);
return 1;
}
// 关闭共享内存对象
close(shm_fd);
// 删除共享内存对象
if (shm_unlink(SHM_NAME) == -1) {
perror("shm_unlink");
return 1;
}
return 0;
}
副端测试
#include <iostream>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#define SHM_NAME "/my_shm"
#define SHM_SIZE 1024
int main() {
// 打开共享内存对象
int shm_fd = shm_open(SHM_NAME, O_RDONLY, 0666);
if (shm_fd == -1) {
perror("shm_open");
return 1;
}
// 将共享内存对象映射到进程的地址空间
const void* ptr = mmap(0, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
return 1;
}
// 读取数据并打印
const char* message = static_cast<const char*>(ptr);
std::cout << "Received message: " << message << std::endl;
// 取消映射共享内存
if (munmap(const_cast<void*>(ptr), SHM_SIZE) == -1) {
perror("munmap");
close(shm_fd);
return 1;
}
// 关闭共享内存对象
close(shm_fd);
return 0;
}
*转载请注明出处:原文链接:https://cpp.vin/page/149.html