我想在兩個進程之間創建一個共享內存。因此,我簡單地複製從Microsoft頁面的剪斷:無法映射共享內存
片段1:
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");
void initSharedMem() {
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) {
MessageBox(0, "Could not create file mapping object", "Error", 0);
return;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL) {
MessageBox(0, "Could not map view of file", "Error", 0);
CloseHandle(hMapFile);
return;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
MessageBox(0, "Done init shared mem", "Done", 0);
return;
}
片段2(其他工序):
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");
void readSharedMem() {
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL) {
MessageBox(0, L"Error", L"Could not open file mapping object", 0);
return;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL) {
MessageBox(0, L"Error", L"Could not map file", 0);
CloseHandle(hMapFile);
return;
}
MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return;
MessageBox(0, L"Done", L"SharedMemoryDone", 0);
}
我調用過程A中的第一功能,並獲得完成的消息。但是當我之後調用readSharedMem函數時,我收到錯誤消息「無法打開文件映射對象」。
我在這裏做錯了什麼?
當您嘗試打開共享內存部分時,您的進程仍然活着嗎?此外,當'OpenFileMapping'失敗時,你會得到什麼樣的錯誤代碼? – IInspectable
提示:永遠不要複製/粘貼代碼。理想情況下,您應該重新輸入代碼,查找您不瞭解的任何內容。這就是你學習新概念的方法。 – CodeMouse92
是的,兩者都還活着,錯誤代碼是2. – QDA