Created
November 18, 2017 04:54
-
-
Save igaozp/34bfe733e698c46eb2496a5dc793e162 to your computer and use it in GitHub Desktop.
进程通过读写内存共享数据
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # include <windows.h> | |
| # include <iostream> | |
| int main(int argc, char* argv[]) | |
| { | |
| HANDLE lhShareMemory; | |
| char* lpcBuffer; | |
| lhShareMemory = OpenFileMapping(FILE_MAP_READ, false, "mySharedMemory"); | |
| if (NULL == lhShareMemory) | |
| { | |
| std::cout << "Open share memory unsuccessfully!" << std::endl; | |
| DWORD ldwError = GetLastError(); | |
| std::cout << ldwError; | |
| return 0; | |
| } | |
| lpcBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_READ, 0, 0, 100); | |
| if (NULL == lpcBuffer) | |
| { | |
| std::cout << "Open share memory unsuccessfully!"; | |
| return 0; | |
| } | |
| std::cout << "进程通信:采用共享内存" << std::endl; | |
| std::cout << "读进程" << std::endl; | |
| std::cout << "读入数据:" << std::endl; | |
| for (int i = 0; i < 100; ++i) | |
| { | |
| std::cout << *(lpcBuffer + i); | |
| } | |
| UnmapViewOfFile(lpcBuffer); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # include <windows.h> | |
| # include <iostream> | |
| int main(int argc, char* argv[]) | |
| { | |
| HANDLE lhShareMemory; | |
| char* lpBuffer = NULL; | |
| lhShareMemory = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE, | |
| 0, 10, "mySharedMemory"); | |
| if (NULL == lhShareMemory) | |
| { | |
| if (ERROR_ALREADY_EXISTS == GetLastError()) | |
| { | |
| std::cout << "Already exists!" << std::endl; | |
| } | |
| else | |
| { | |
| std::cout << "Create Sheared Memory unsuccessfully!" << std::endl; | |
| } | |
| return 0; | |
| } | |
| lpBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_WRITE, 0, 0, 10); | |
| if (NULL == lpBuffer) | |
| { | |
| std::cout << "Get Share memory unsuccessfully!" << std::endl; | |
| return 0; | |
| } | |
| strcpy(lpBuffer, "hello"); | |
| std::cout << "进程通信:采用共享内存" << std::endl; | |
| std::cout << "写进程" << std::endl; | |
| std::cout << "写入数据:" << std::endl << lpBuffer << std::endl; | |
| Sleep(100000); | |
| UnmapViewOfFile(lpBuffer); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment