【发布时间】:2014-11-02 21:19:28
【问题描述】:
我正在尝试编写一个只允许运行一个程序实例的SingleApplication 类。我正在使用QSharedMemory
程序运行良好,除非我使用值为"42" 的键。我做错了什么吗?这是未定义的行为吗?
Main.cpp
int main(int argc, char *argv[])
{
//QApplication a(argc, argv);
SingleApplication a(argc, argv, "42"); //Does not work with '42'. Will work for any other value.
MainWindow w;
w.show();
return a.exec();
}
SingleApplication.h
class SingleApplication : public QApplication
{
Q_OBJECT
public:
SingleApplication(int &argc, char *argv[], const QString uniqueKey);
bool alreadyExists() const{ return bAlreadyExists; }
bool isMasterApp() const { return !alreadyExists(); }
bool sendMessage(const QString &message);
public slots:
//void checkForMessages();
signals:
//void messageAvailable(const QStringList& messages);
private:
bool bAlreadyExists;
QSharedMemory sharedMemory;
};
SingleApplication.cpp
SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv){
sharedMemory.setKey(uniqueKey);
//Create if one does not exist already
if(sharedMemory.create(5000))
{
qDebug() << "Created!";
bAlreadyExists = false;
}
else{
if(sharedMemory.error() == QSharedMemory::AlreadyExists){
qWarning() << "Program is already running!";
}
}
}
【问题讨论】:
-
具体错误是什么?
-
@Oncaphillis
sharedMemory.create()只是返回 false。即使是第一次运行程序。 -
共享内存段“42”是否已被另一个进程/线程使用?我现在才 shm 从 linux 和密钥只是不同进程可能相同的数字。但是,有些助手应该可以帮助您保持它们的独特性。尝试使用列出当前 shm 段的工具。
-
@EngieOP:errorString() 说什么?我不明白你的用例和实现。
-
42 在整个银河系中全局分配 ;-)
标签: c++ qt shared-memory qtcore qsharedmemory