Hi,
I have a publisher and subscriber kind of a project.
- I am using CreateFileMappingW API to create a shared memory.
- Subscriber starts first, It will create a named shared memory using lpName argument.
- 2 publishers starts next, both will try to connect to the same shared memory which Subscriber created above.
My Use case is :-
- Subscriber will be reading the data present in shared memory.
- A batch file runs the 2 publishers.
- Each publisher when run, will map to the existing Shared memory and will write 10 packets of data to Shared memory and then they exit.
- After exit, Batch file runs the 2 publishers again.
This use case is working fine for some iterations.
But after 30 to 40 Iterations, when Publisher is trying to map to the existing Shared memory using CreateFileMappingW API, the API is creating a new Shared memory. There is no failure also, GetLastError() also returned SUCCESS. Hence publisher is writing data to that newly created shared memory, but Subscriber is not able to receive, as it is trying to rad data from already existing Shared memory.
Publisher is writing 10 packets to newly Created Shared memory and it exit.
When batch file runs the publisher again, it properly maps to the correct Shared memory and everything works fine.
This issue is happening once in a while after around 30 to 40 iterations.
Kindly let me know how to handle this issue.
Below is the code for both Publisher and Subscriber applications for Initialising the Shared memory.
int ShmInitialize(const char* keyFilePath, unsigned long shmMemSize)
{
HANDLE iShmId = NULL;
int i = 0;
/* Key file path is null /
if (keyFilePath == NULL)
{
printf("SHM_KEY_FILE_PATH ERROR ");
return -1;
}
/ Key file present in the requested path */
if (access(keyFilePath, F_OK) == -1)
{
printf("SHM_KEY_FILE_PATH ACCESS ERROR ");
return -1;
}
iShmId = CreateFileMappingW(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
(DWORD)shmMemSize, // maximum object size (low-order DWORD)
(LPCWSTR)keyFilePath); // name of mapping object
if (iShmId == NULL)
{
printf("Failed : File mapping object returned (%d). For File: %s\n", GetLastError(), keyFilePath);
return -1;
}
else
{
DWORD lastError = GetLastError();
printf("Create file mapping object returned (%d). For File: %s \n", lastError, keyFilePath);
char* shmAddress = (char*)MapViewOfFile(iShmId, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
shmMemSize);
}
//...
//Other Processing
}
Kindly let me know how to resolve this issue.
Hoping for a solution.
Thanks in anticipation.
Santosh.