程序間通訊之共享記憶體(Share Memory)
阿新 • • 發佈:2018-12-30
為了實現多個程序之間的通訊,我們可以用系統頁面檔案來作為共享記憶體檔案。
1.首先我們建立第一個程序,用系統函式CreateFileMapping建立共享記憶體檔案,用函式MapViewOfFile對映共享記憶體檔案到程序,具體操作見程式碼:
#include <Windows.h>
#include <conio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
const size_t BUF_SIZE = 256;
TCHAR szName[]=TEXT("Local\\MyFileMappingObject" );
TCHAR szMsg[]=TEXT("Message from first process.");
int main(void)
{
HANDLE hAndle = CreateFileMapping(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
BUF_SIZE,
szName);
if (NULL == hAndle)
{
cout<<"Could not create file mapping object:" <<GetLastError()<<endl;
return EXIT_FAILURE;
}
LPCTSTR pBuf = (LPCTSTR)MapViewOfFile(hAndle,
FILE_MAP_ALL_ACCESS,
0,
0,
BUF_SIZE);
if (NULL == pBuf)
{
cout<<"Could not map view of file :"<<GetLastError()<<endl;
CloseHandle(hAndle);
return EXIT_FAILURE;
}
CopyMemory((PVOID)pBuf,szMsg,(_tcslen(szMsg)*sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hAndle);
return EXIT_SUCCESS;
}
2.這下我們可以建立第二個程序對共享記憶體檔案訪問,用系統函式OpenFileMapping開啟記憶體對映檔案物件,具體操作見如下程式碼:
#include <Windows.h>
#include <iostream>
using namespace std;
const size_t BUF_SIZE = 256;
TCHAR szName[]=TEXT("Local\\MyFileMappingObject");
int main(void)
{
HANDLE hAndle = OpenFileMapping(FILE_MAP_ALL_ACCESS,false,szName);
if (NULL == hAndle)
{
cout<<"Could not open file mapping object :"<<::GetLastError()<<endl;
return EXIT_FAILURE;
}
LPCTSTR pBuf = (LPCTSTR)MapViewOfFile(hAndle,
FILE_MAP_ALL_ACCESS,
0,
0,
BUF_SIZE);
if (NULL == pBuf)
{
cout<<"Could not map view of file :"<<GetLastError()<<endl;
CloseHandle(hAndle);
return EXIT_FAILURE;
}
MessageBox(NULL,pBuf,TEXT("Process2"),MB_OK);
UnmapViewOfFile(hAndle);
CloseHandle(hAndle);
return EXIT_SUCCESS;
}
3.執行時執行第一個程序後執行第二個程序,第二個程序能夠獲取到第一個程序的資訊,這樣我們程序間通訊已經完整完成。