程序单例化

用QT实现程序的单例化有很多方法,但我觉得最方便,最实用的还是以下的这一种。

以下是一个例子程序:


#include <QtGui/QApplication>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QSharedMemory>

int main(int argc, char **argv)
{
	QApplication app(argc, argv);

	QSharedMemory *shareMem = new QSharedMemory(QString("SingleInstanceIdentify"));
	int i = 2;
	while(i--)
	{
		if (shareMem->attach(QSharedMemory::ReadOnly))
			shareMem->detach();
	}

	if (shareMem->create(1))
	{
		QLabel *label = new QLabel("Hello, world");
		label->resize(100, 100);
		label->show();
		app.exec();

		if (shareMem->isAttached())
			shareMem->detach();
		delete shareMem;
	}
	else
		QMessageBox::information(NULL, "Error",  "The programming is runing");
}


你可能感兴趣的:(程序单例化)