我正在尝试使用文件映射在C语言中构建客户端/服务器程序,虽然开发仍处于早期阶段,但我还是有些困惑,不太理解文件映射的工作原理。
我在服务器上创建了一个结构体的文件映射,并放置了一些数据。然后我的客户端打开了这个文件映射,成功读取了数据。接着客户端写入数据让服务器读取,但是服务器无法读取客户端的数据,我无法理解其中的原因,因为该文件映射应该在两个进程之间同步。目前我还没有使用事件,但我认为不需要使用它们(需要吗?)
以下是我的代码:
服务器端:
struct _HBACKUPSERVICE{
DWORD dwServerProcessID;
TCHAR szWork[MAX_PATH];
HANDLE hMapFile;
};
PHBACKUPSERVICE pBuf = NULL;
HANDLE hMapFile;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
sizeof(HBACKUPSERVICE), // maximum object size (low-order DWORD)
_T("MyService")); // name of mapping object
if (/*phBackupService->*/hMapFile == NULL){
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return *pBuf;
}
pBuf = (PHBACKUPSERVICE)MapViewOfFile(
hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(HBACKUPSERVICE));
if (pBuf == NULL){
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
return *pBuf;
}
// Populate backup service structure
pBuf->hMapFile = hMapFile;
pBuf->dwServerProcessID = GetCurrentProcessId();
// Wait for client
do{
_tprintf(_T("\nServer: Waiting for work."));
pBuf = (PHBACKUPSERVICE)MapViewOfFile(
_BackupService.hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(HBACKUPSERVICE));
if (StringCbLength(pBuf->szWork, 1 * sizeof(TCHAR), NULL) == S_OK){ Sleep(500); }
} while (StringCbLength(pBuf->szWork, 1 * sizeof(TCHAR), NULL) == S_OK); // ERROR: pBuf->szWork is always empty...
_tprintf(_T("Work from client: %s"), pBuf->szWork);
客户端:
HBACKUPSERVICE _BackupService;
HANDLE hMapFile;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
_T("MyService")); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
}
BackupService= (PHBACKUPSERVICE)MapViewOfFile(
hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(HBACKUPSERVICE));
_tprintf(_T("Server process id: %d"), _BackupService.dwServerProcessID);
_tprintf(_T("send work to server"));
StringCchCopy(_BackupService.szWork, STRSAFE_MAX_CCH, _T("Do work for me!!!!!!!!!!")); //ERROR: the server never sees this
谢谢!