linux 进程间共享内存示例
Posted 空明流光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux 进程间共享内存示例相关的知识,希望对你有一定的参考价值。
写入端:
#include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/shm.h> using namespace std; struct MappingDataType { int mappingData; }; bool SetUsedPID(string mappingName) { void *shm = NULL; MappingDataType *shared; int shmid = shmget((key_t)1234, sizeof(MappingDataType), 0666|IPC_CREAT); if(shmid == -1) { fprintf(stderr, "shmget failed "); return false; } shm = shmat(shmid, 0, 0); if(shm == (void*)-1) { fprintf(stderr, "shmat failed "); return false; } shared = (MappingDataType*)shm; shared->mappingData = ::getpid(); /*if(shmdt(shm) == -1) { fprintf(stderr, "shmdt failed "); return false; } if(shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr, "shmctl(IPC_RMID) failed "); return false; }*/ return true; } int main(int argc, char *argv[]) { bool result = SetUsedPID("abc"); //打断点,运行读取端 cout << result << endl; return 0; }
读取端:
#include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/shm.h> using namespace std; struct MappingDataType { int mappingData; }; int GetUsedPID(string mappingName) { void *shm = NULL; MappingDataType *shared; int shmid = shmget((key_t)1234, sizeof(MappingDataType), 0666 | IPC_CREAT); if (shmid == -1) { fprintf(stderr, "shmget failed "); return 0; } shm = shmat(shmid, 0, 0); if (shm == (void*)-1) { fprintf(stderr, "shmat failed "); return 0; } shared = (struct MappingDataType*)shm; int pid = shared->mappingData; if (shmdt(shm) == -1) { fprintf(stderr, "shmdt failed "); } if (shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr, "shmctl(IPC_RMID) failed "); } return pid; } int main(int argc, char *argv[]) { int pid = GetUsedPID("abc"); cout << pid << endl; //<================= Put a breakpoint here return 0; }
以上是关于linux 进程间共享内存示例的主要内容,如果未能解决你的问题,请参考以下文章
linux两个进程间共享内存通信都需要调用shmget函数么
Linux 内核 内存管理内存管理系统调用 ⑤ ( 代码示例 | 多进程共享 mmap 内存映射示例 )