共享内存的使用
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring> // For strcpy function
int main() {
// 创建一个共享内存段
key_t key = ftok("/tmp", 'A');
int shm_id = shmget(key, 1024, IPC_CREAT | 0666);
// 将共享内存段映射到进程的地址空间中
char *shm_ptr = (char *)shmat(shm_id, NULL, 0);
// 在共享内存中写入数据
std::string message = "Hello from shared memory!";
std::strcpy(shm_ptr, message.c_str());
std::cout << "Data written to shared memory: " << message << std::endl;
// 解除共享内存映射
//shmdt(shm_ptr);
// 删除共享内存段
//shmctl(shm_id, IPC_RMID, NULL);
return 0;
}
编译执行
g++ test.cpp
./a.out
ipcs -m
输出结果
(base) mazu@tegra-ubuntu-s2:~/hq$ ./a.out
Data written to shared memory: Hello from shared memory!
(base) mazu@tegra-ubuntu-s2:~/hq$ ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x411d0001 1 mazu 666 1024 0