One of Qt’s solutions is a class called QtSharedMemory. It lets you share and lock memory between two processes on the same system. Originally written for Qt3 and then ported to Qt4 I set aside some time and created the successors of this class which will be part of Qt 4.4. The locking capability found in QtSharedMemory is useful for cases other then just shared memory and it was taken out and made into its own class. A better API and a nice example the code is in 4.4 and can be seen in the snapshots today.
Here is a “Hello world” shared memory example.
First process A would do the following:
QSharedMemory sharedMemory("foobar"); sharedMemory.create(1024); sharedMemory.lock(); char *to = (char*)sharedMemory.data(); char *text = "hello world"; memcpy(to, text, strlen(text)+1); sharedMemory.unlock();
And then until process A destroyed its sharedMemory variable process B can access the “hello world” data.
QSharedMemory sharedMemory("foobar"); sharedMemory.attach(); sharedMemory.lock(); char *to = (char*)sharedMemory.data(); qDebug() << to; sharedMemory.unlock();
QSharedMemory uses the second new class, QSystemSemaphore to provide system wide locking. This is useful when you have different processes accessing the same data. If you are using threads you should use QSemaphore which is much lighter and has more capabilities. Check out the shared memory example documentation which walks through more detailed usage of shared memory.
Due to the different ways that every platform implement these features there are a few exceptions to be away of and they are documented in the class description (for example on HP-UX only one attach to a shared memory segment is allowed per process). QtSharedMemory and QSharedMemory and incompatible to prevent accidentally using them together and it is advisable to stick with one or the other.
The API for these classes has gone through a number of revisions. Check out the class API’s and example and let us know what you think.