完成研究之后,关于如何在C ++中的两个独立应用程序之间共享内存并没有很好的堆栈溢出,这些应用程序随附代码。
一个解决方案可以在这里找到:How to use shared memory with Linux in C
但它需要一个进程分叉,以便内存mmap
到同一位置。它不适用于两个单独的应用程序。
什么是编写两个使用内存空间共享数据的应用程序的最有效方法?
这是我使用shmget
的解决方案,它过时了,但它的工作原理
主办:
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
char output[] = "test";
int shmid=shmget(IPC_PRIVATE, sizeof(output), 0666);
FILE *fp;
fp = fopen("/tmp/shmid.txt", "w+");
fprintf(fp, "%d", shmid);
fclose(fp);
int *mem_arr;
while(true)
{
mem_arr = (int *)shmat(shmid, NULL, 0);
memcpy(mem_arr, output, sizeof(output));
shmdt(mem_arr);
}
return 1;
}
客户:
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
char output[] = "test";
FILE *fp;
fp = fopen("/tmp/shmid.txt", "r");
int shmid;
fscanf (fp, "%d", &shmid);
fprintf(fp, "%d", shmid);
fclose(fp);
while(true)
{
int* shared_mem = (int *)shmat(shmid, NULL, 0);
printf("data: %s\n", shared_mem);
}
return 1;
}