#include <QSharedMemory>
#include <QDebug>
bool shmCreate( QSharedMemory & qs )
{
qDebug( ) << "About to create shared memory. Press key to execute.";
getchar( );
qDebug( ) << "\nShared memory creation in progress...\n";
if( qs.create( 10 ) )
{
qDebug( ) << "Shared memory successfully created.\n";
return true;
}
else
{
qDebug( ) << "Shared memory creation failed.\n";
qDebug( ) << qs.errorString( ) << "\n";
return false;
}
}
bool shmAttach( QSharedMemory & qs )
{
qDebug( ) << "About to attach to shared memory. Press key to execute.";
getchar( );
qDebug( ) << "\nAttaching to shared memory...\n";
if( qs.attach( ) )
{
qDebug( ) << "Shared memory successfully attached.\n";
return true;
}
else
{
qDebug( ) << "Attaching to shared memory failed.\n";
qDebug( ) << qs.errorString( ) << "\n";
return false;
}
}
void shmLock( QSharedMemory & qs )
{
qDebug( ) << "About to lock shared memory. Press key to execute.\n";
getchar( );
qDebug( ) << "\nLocking shared memory...\n";
if( qs.lock( ) )
{
qDebug( ) << "Shared memory successfully locked.\n";
}
else
{
qDebug( ) << "Locking shared memory failed.\n";
qDebug( ) << qs.errorString( ) << "\n";
}
}
void shmUnlock( QSharedMemory & qs )
{
qDebug( ) << "About to unlock shared memory. Press key to execute.";
getchar( );
qDebug( ) << "\nUnocking shared memory...\n";
if( qs.unlock( ) )
{
qDebug( ) << "Shared memory successfully unlocked.\n";
}
else
{
qDebug( ) << "\nUnlocking shared memory failed.\n";
qDebug( ) << qs.errorString( ) << "\n";
}
}
void shmDetach( QSharedMemory & qs )
{
qDebug( ) << "About to detach from shared memory. Press key to execute.";
getchar( );
qDebug( ) << "\nDetaching from shared memory...\n";
if( qs.detach( ) )
{
qDebug( ) << "Successfully detached from shared memory.\n";
}
else
{
qDebug( ) << "\nDetaching from shared memory failed.\n";
qDebug( ) << qs.errorString( ) << "\n";
}
}
#define REVERSE REVERSE
int main(int argc, char *argv[])
{
QSharedMemory qs( "TEST" );
while( true )
{
#ifdef REVERSE
// Attach, then create.
if( shmAttach( qs ) ) break;
if( shmCreate( qs ) ) break;
#else
// Create, then attach.
if( shmCreate( qs ) ) break;
if( shmAttach( qs ) ) break;
#endif
if(qs.error() == QSharedMemory::AlreadyExists || qs.error() == QSharedMemory::NotFound)
qDebug( ) << "\nRetry again ...";
else{
qDebug( ) << "\nError occurred. Cannot continue. Terminate application.\n";
return 0;
}
}
shmLock ( qs );
qDebug( ) << "\nDo critical stuff...\n";
shmUnlock( qs );
shmDetach( qs );
return 0;
}
Bookmarks