Windows共享内存
2013-07-09 11:01
66 查看
以下有2个进程,a.cpp生成A进程,b.cpp生成b进程。那么a进程将不停地读名为"Global\\MyFileMappingObject"的共享内存块,而b进程不停地写名为"Global\\MyFileMappingObject"的共享内存块。从而实现IPC。
//a.cpp #include <windows.h> #include <string.h> #include <string> #include <iostream> #include <tchar.h> using namespace std; #define BUF_SIZE 256 TCHAR szName[]=TEXT("Global\\MyFileMappingObject"); //指向同一块共享内存的名字 int main(int argc, char *argv[]) { HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } //从main开始至此,A B process代码一样,都是获取名为"Global\\MyFileMappingObject"的共享内存的指针 //以下代码,A不停地读共享内存pBuf while(1) { cout<<pBuf<<endl; cout<<"A process: hit keyboard to receive from B process"<<endl; getchar(); } UnmapViewOfFile(pBuf); CloseHandle(hMapFile); return 0; }
//b.cpp #include <iostream> #include <Windows.h> #include <tchar.h> using namespace std; #define BUF_SIZE 256 TCHAR szName[]=TEXT("Global\\MyFileMappingObject"); //指向同一块共享内存的名字 int main() { HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } //从main开始至此,A B process代码一样,都是获取名为"Global\\MyFileMappingObject"的共享内存的指针 //以下代码,B不停写共享内存pBuf while(1) { TCHAR s[BUF_SIZE]; cout<<"B process: plz input sth. to be transfered to A process."<<endl; cin>>s; memcpy((PVOID)pBuf, s, BUF_SIZE); } }
相关文章推荐
- Windows进程间通信-共享内存
- Windows 程序设计 第二十一章 DLL中共享内存数据
- Windows进程间通信之共享内存
- windows下利用文件映射实现共享内存
- windows下利用文件映射实现共享内存
- Windows系统服务与用户进程共享内存
- 在驱动和应用程序间共享内存 分类: windows驱动程序WDM 2013-09-25 14:37 650人阅读 评论(0) 收藏
- Windows进程间通信:共享内存
- windows笔记-使用内存映射文件在进程之间共享数据
- Windows进程间通信--共享内存
- windows学习历程-IPC之共享内存
- Windows共享内存 C++及C#实现
- windows 进程间通信(共享内存)
- Windows进程间通信-共享内存
- windows 下共享内存使用方法示例
- Windows共享内存解析
- Windows进程通信 -- 共享内存
- Windows进程间共享内存通信实例
- Windows驱动中通过MDL实现用户态与核心态共享内存
- Windows 进程间通信(八)共享内存(FileMapping)