I am trying to use Poco SharedMemory object and I am having some problems.
I am on Linux (2.6.26), and using Poco 1.3.1-p1-all
What I want to do is to create a 'server' process that will initialize a shared memory segment and stay up, and a few client processes that will access that shared memory but not change it.
I noticed two problems:
1. if I open a AM_READ instance:
- Code: Select all
SharedMemory shared("shared", size, SharedMemory::AM_READ, 0, true);
it fails with this exception:
Exception : Cannot resize shared memory object: /shared
when it tries to ftrucate the fd.
2. if I open the client with AM_WRITE, it works - but the memory actually contains the shared data only for the first client process. the rest gets uninitialized data (all zeros).
here is my sample application, help would be appreciated:
I already tried to play with the server flag, and I don't think it made any difference with this behavior.
- Code: Select all
#include <iostream>
#include <string.h>
#include "Poco/SharedMemory.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
#include "Poco/File.h"
using Poco::SharedMemory;
using Poco::SystemException;
using Poco::Thread;
using Poco::File;
using namespace std;
long checksum(char *start, char *end);
int main(int argc, char** argv)
{
if (argc < 2)
{
cout << "Usage: PocoTest [server|client]" << endl;
exit(1);
}
size_t size = 10000;
try
{
if (strcmp(argv[1], "server") == 0)
{
cout << "Starting shared memory server" << endl;
SharedMemory shared("shared", size, SharedMemory::AM_WRITE, 0, true);
char *start = shared.begin();
char *end = shared.end();
while(start++ < end) *start = 1;
long long check = checksum(shared.begin(), shared.end());
cout << "Checksum on server : " << check << endl;
while(1)
{
Thread::sleep(7000);
check = checksum(shared.begin(), shared.end());
cout << "Checksum on server : " << check << endl;
}
return 0;
}
else
{
cout << "Starting shared memory client" << endl;
SharedMemory shared("shared", size, SharedMemory::AM_READ, 0, true);
cout << "Checksum on client : " << checksum(shared.begin(), shared.end()) << endl;
}
}
catch (SystemException ex)
{
cout << "Exception : " << ex.message() << endl;
}
catch (...)
{
cout << "Unhandled exception" << endl;
}
}
long checksum(char *start, char *end)
{
long long checksum = 0;
while(start < end) checksum += *start++;
return checksum;
}





