- 当我们想让程序只可以启动一个,防止多个启动时,可以使用共享内存QSharedMemory的方式现实。
- 代码如下,注意
uniqueId
要唯一
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString uniqueId = "AppId";
QSharedMemory sharedMemory(uniqueId);
if (sharedMemory.attach())
{
qint64 *runningInstance = static_cast<qint64 *>(sharedMemory.data());
if (runningInstance && *runningInstance != 0)
{
QProcess process;
process.start("pidof", QStringList() << QString::number(*runningInstance));
process.waitForFinished();
if (!process.readAllStandardOutput().isEmpty())
{
QMessageBox::warning(nullptr, QObject::tr("警告"),
QObject::tr("程序已经在运行!"));
sharedMemory.detach();
return 0;
}
}
sharedMemory.detach();
}
if (sharedMemory.create(sizeof(qint64)))
{
qint64 *runningInstance = static_cast<qint64 *>(sharedMemory.data());
*runningInstance = QCoreApplication::applicationPid();
QObject::connect(&a, &QApplication::aboutToQuit, [&]()
{
if (sharedMemory.isAttached())
{
qint64 *runningInstance = static_cast<qint64*>(sharedMemory.data());
if (runningInstance) *runningInstance = 0;
sharedMemory.detach();
} });
return a.exec();
}
else
{
QMessageBox::information(nullptr, QObject::tr("提示"),
QObject::tr("程序已经在运行!"));
return 1;
}
}