ac linux上,我们可以用检测进程列表来得知是否当前应用程序已经运行来保证我们的程序只有一份处于运行时。
在QT里面,我们可以使用QtSingleApplication来实现单例,但是这个类却没有被包含在开源版里,只有商业版才拥有,(爆料下,QT的商业版要50000多一个license)。下面我们使用QShareMemory来实现这个功能:
代码如下:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSharedMemory *shareMem = new QSharedMemory(QString("SingleInstanceIdentify"));
/* if the sharedmemory has not been created, it returns false, otherwise true.
* But if the application exit unexpectedly, the sharedmemory will not detach.
* So, we try twice.
*/
volatile short i = 2;
while (i--)
{
if (shareMem->attach(QSharedMemory::ReadOnly)) /* no need to lock, bcs it's read only */
{
shareMem->detach();
}
}
if (shareMem->create(1))
{
MainWindow w;
w.show();
a.exec();
if (shareMem->isAttached())
shareMem->detach();
delete shareMem;
}
return 0;
}
|
|
|
阅读(6241) | 评论(0) | 转发(0) |