共享内存由文件支持是否重要?如果没有,您可以考虑使用底层的 Unix 共享内存 API:shmget、shmat、shmdt 和 shmctl,它们都在 sys/shm.h 中声明。我发现它们非常易于使用。
// create some shared memory
int id = shmget(0x12345678, 1024 * 1024, IPC_CREAT | 0666);
if (id >= 0)
{
void* p = shmat(id, 0, 0);
if (p != (void*)-1)
{
initialize_shared_memory(p);
// detach from the shared memory when we are done;
// it will still exist, waiting for another process to access it
shmdt(p);
}
else
{
handle_error();
}
}
else
{
handle_error();
}
另一个进程会使用这样的东西来访问共享内存:
// access the shared memory
int id = shmget(0x12345678, 0, 0);
if (id >= 0)
{
// find out how big it is
struct shmid_ds info = { { 0 } };
if (shmctl(id, IPC_STAT, &info) == 0)
printf("%d bytes of shared memory\n", (int)info.shm_segsz);
else
handle_error();
// get its address
void* p = shmat(id, 0, 0);
if (p != (void*)-1)
{
do_something(p);
// detach from the shared memory; it still exists, but we can't get to it
shmdt(p);
}
else
{
handle_error();
}
}
else
{
handle_error();
}
然后,当所有进程都使用共享内存时,使用shmctl(id, IPC_RMID, 0)
将其释放回系统。
您可以在命令行中使用 ipcs 和 ipcrm 工具来管理共享内存。当第一次编写共享内存代码时,它们对于清理错误很有用。
尽管如此,我不确定在 32 位和 64 位程序之间共享内存。我建议尝试 Unix API,如果失败,可能无法完成。毕竟,它们是 Boost 在其实现中使用的。