Chinaunix首页 | 论坛 | 博客
  • 博客访问: 533731
  • 博文数量: 78
  • 博客积分: 1913
  • 博客等级: 上尉
  • 技术积分: 829
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-14 21:29
文章分类

全部博文(78)

文章存档

2011年(27)

2010年(26)

2009年(20)

2008年(5)

我的朋友

分类: C/C++

2010-05-27 15:52:07

    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;
}




阅读(6176) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~