So I am trying to pass an integer an a =3 , from Server side to Client.The problem is that when i do printf of the message on the Client side, instead of 3 the value displayed is a random number ( something like 19923).I was trying to pass the a by value(&a) at the server side but then the value displayed was a heart shape.Please see what is wrong with that communication.Thanks in advance.
//Server
#include <windows.h>
#define BUF_SIZE 256
LPSTR szMapName = "MyFileMappingObject";
int main(void)
{
int a = 3;
HANDLE hMapFile;
LPVOID lpMapAddress;
BOOL bRet;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, /* use swap, not a particular file */
NULL, /* default security */
PAGE_READWRITE, /* read/write access */
0, /* maximum object size (high-order DWORD) */
1024, /* maximum object size (low-order DWORD) */
szMapName); /* name of mapping object */
if (hMapFile == INVALID_HANDLE_VALUE){
printf("CreateFileMapping error %lu",GetLastError());
}
lpMapAddress = MapViewOfFile(
hMapFile, /* handle to map object */
FILE_MAP_ALL_ACCESS, /* read/write permission */
0, /* offset (high-order) */
0, /* offset (low-order) */
0);
if (lpMapAddress == NULL)
printf("MapViewOfFile error");
//ZeroMemory(lpMapAddress, strlen(szMsg) + 1);
CopyMemory(lpMapAddress, a, sizeof(a));
Sleep(10000);
bRet = UnmapViewOfFile(lpMapAddress);
if (bRet == FALSE)
printf("UnampViewOfFile error");
bRet = CloseHandle(hMapFile);
if (bRet == FALSE)
printf("CloseHandle error");
return 0;
}
//Client
#include <windows.h>
#include <stdio.h>
#define BUF_SIZE 256
LPSTR szMapName = "MyFileMappingObject";
int main(void)
{
HANDLE hMapFile;
LPVOID lpMapAddress;
BOOL bRet;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, /* read/write access */
FALSE, /* do not inherit the name */
szMapName); /* name of mapping object */
if (hMapFile == INVALID_HANDLE_VALUE){
printf("CreateFileMapping error %lu",GetLastError());
return 1;
}
lpMapAddress = MapViewOfFile(
hMapFile, /* handle to map object */
FILE_MAP_ALL_ACCESS, /* read/write permission */
0, /* offset (high-order) */
0, /* offset (low-order) */
0);
if (lpMapAddress == NULL){
printf("MapViewOfFile error %d",GetLastError());
return 1;
}
printf("Message from server is: %d\n", lpMapAddress);
bRet = UnmapViewOfFile(lpMapAddress);
if (bRet == FALSE){
printf("UnampViewOfFile");
return 1;
}
bRet = CloseHandle(hMapFile);
if (bRet == FALSE){
printf("CloseHandle");
return 1;
}
return 0;
}
This is incorrect:
as
lpMapAddressis of typeLPVOID(avoid*) so this will print the memory address to whichlpMapAddresspoints, not an integer value. (Just to note that%pmust be used to print a pointer value).Based on the technique used to write the
intto the shared memory:to extract the
intwould be the inverse:Note that the format specifier is missing from the following line:
should be: