<Solved>QSharedMemory : Second process cannot attach
-
I have 2 processes.
The first one creates a QSharedMemory, with a key.
The creation is successful, as no error is returned.
In the second process, I try and attach to the shared memory, having done
setKey()
with the same key name as the first process, and then try andattach()
to the memory.The
attach()
fails. UsingerrorString()
on the shared memory, the following string is returned :bq. QSharedMemory::handle: doesn’t exist
This is how I create the Shared Memory for the first instance
@
sharedMem = new QSharedMemory("GSASharedMemory");
bool checkcreate = sharedMem->create(size);
if (!checkcreate)
Logger::WriteLog("Instance 1 : Cannot create shared memory" );
QString tempstrcreate = sharedMem->errorString();
tempstrcreate.prepend("Instance 1:");
Logger::WriteLog(tempstrcreate);bool checkattach = sharedMem->isAttached(); if(checkattach) Logger::WriteLog("Instance 1 : memory created and attached" ); QString temp1 = "creating mutex with:"; temp1.append(temp); Logger::WriteLog(temp);
@
This works fine. So the memory is created and is attached to.
Next, while this is running...@
sharedMem = new QSharedMemory();
sharedMem->setKey("GSASharedMemory");
bool attachMem = sharedMem->attach();
if(!(sharedMem->attach()))
Logger::WriteLog("Cannot attach to shared Memory" );
else{
QString errorstr = sharedMem->errorString();
Logger::WriteLog(errorstr);
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << P14TagName;
size = buffer.size();
/* bool checkMemoryCreation = sharedMem->create(size);
if (!checkMemoryCreation) {
Logger::WriteLog("Cannot create Shared Memory" );
return 0;
}
else*/
sharedMem->lock();
char to = (char)sharedMem->data();
QString totemp = QString::fromUtf8(to);
qDebug()<<totemp;
const char *from = buffer.data().data();
QString totemp1 = from;
totemp1.append(totemp);
Logger::WriteLog(totemp1);
memcpy(to, from, qMin(sharedMem->size(), size));
QString tempKey = sharedMem->key();
tempKey.append(" ::Written name into shared Memory");
@The attach fails. And I get the aforementioned error.
What could I be missing here? Kindly advise, thanks.
-
It would be easier for us to help you if you show us the code you use to create/attach the QSharedMemory.
-
Updated. Kindly check and advise.
-
Are you sure that the process that created the QSharedMemory is still running while your second process tries to attach it ?
-
Yes, the process that created the shared memory is still running when the second process tries to attach to it. No ambiguity there.
-
Anyone, please? This is driving me wild...
-
Solved. Stray detach() statement, which would detach the first process from the memory,before the second had a chance to attach to it, hence it couldn't find a handle to it.