我想写一个SingleApplication
类,它只允许程序的一个实例运行。我正在使用QSharedMemory
QSharedMemory :: create()问题
该程序工作正常,除非我使用的值为"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 2014-11-02 22:02:39
@Oncaphillis'sharedMemory.create()'只是返回false。即使是第一次运行程序。 – 2014-11-02 22:12:40
难道共享内存段“42”已被其他进程/线程使用吗?我现在只从shm linux和keys只是不同的进程可能是相同的数字。然而,有些帮手会帮助你保持独特。尝试一个列出currenr shm段的工具。 – Oncaphillis 2014-11-02 22:15:38