Reputation: 1475
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 and attach()
to the memory.
The attach()
fails. Using errorString()
on the shared memory, the following string is returned :
QSharedMemory::handle: doesn't exist
Platform is Windows.
What could I be missing here? Kindly advise, thanks.
Upvotes: 1
Views: 7318
Reputation: 1
Encountered same problem. Make sure that QSharedMemory object still lives when second binary tries to attach. If you want to block ability to run 2 instances of same QT binary, just make QSharedMemory object using dynamic memory which will live until app exit.
Upvotes: 0
Reputation: 19112
Have you looked at the shared memory example?
http://doc-snapshot.qt-project.org/4.8/ipc-sharedmemory.html
Below are some code snippets from that example.
Here is what the first process does to put a buffer of "size" into the shared memory:
if (!sharedMemory.create(size)) {
ui.label->setText(tr("Unable to create shared memory segment."));
return;
}
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();
Here is what happens when the second process wants to access the shared memory:
if (!sharedMemory.attach()) {
ui.label->setText(tr("Unable to attach to shared memory segment.\n" \
"Load an image first."));
return;
}
QBuffer buffer;
QDataStream in(&buffer);
QImage image;
sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> image;
sharedMemory.unlock();
sharedMemory.detach();
ui.label->setPixmap(QPixmap::fromImage(image));
Note also that in the example, both processes must be running and still have their instance of QSharedMemory. Here is how it is described in the documentation:
Windows: QSharedMemory does not "own" the shared memory segment. When all threads or processes that have an instance of QSharedMemory attached to a particular shared memory segment have either destroyed their instance of QSharedMemory or exited, the Windows kernel releases the shared memory segment automatically.
Hope that helps.
Upvotes: 1