[英]How to compile (build) my Qt application to run on many linux distributions?
[英]How to force my application to open one exe only? qt, linux
我希望我的應用程序只打開一個進程,即如果一個進程已經打開並且用戶想要再次打開exe - 它將不會打開另一個進程。
我怎么能在Qt-linux中做到這一點?
10倍!
您正在尋找的是QtSingleApplication
。
如果您啟動應用程序的另一個實例,第一個應用程序甚至會得到通知(您可以傳遞您想要的任何數據結構)。
每當啟動另一個實例時,我就用它將現有應用程序帶到前面。
在main.cpp中使用以下代碼可防止運行多個應用程序實例。 我在Linux下(在QtCreator中)測試了這個代碼並且它可以工作(也適用於Windows)。 我覺得這個解決方案簡單易行。 該示例適用於控制台應用程序。 對於GUI應用程序,代碼保持不變,請檢查代碼中的注釋。
//main.cpp
#include <QCoreApplication> //Console application
//#include <QApplication> //GUI application
#include <QSharedMemory>
#include <QDebug>
//Your QMainWindow derivated class goes here :
//#include "MainWindow.h"
int main(int argc, char *argv[])
{
QCoreApplication app( argc, argv );
app.processEvents();
//---- Check for another instance code snippet ----
//GUID : Generated once for your application
// you could get one GUID here: http://www.guidgenerator.com/online-guid-generator.aspx
QSharedMemory shared("62d60669-bb94-4a94-88bb-b964890a7e04");
if( !shared.create( 512, QSharedMemory::ReadWrite) )
{
// For a GUI application, replace this by :
// QMessageBox msgBox;
//msgBox.setText( QObject::tr("Can't start more than one instance of the application.") );
//msgBox.setIcon( QMessageBox::Critical );
//msgBox.exec();
qWarning() << "Can't start more than one instance of the application.";
exit(0);
}
else {
qDebug() << "Application started successfully.";
}
//---- END OF Check for another instance code snippet ----
// Only one instance is running, declare MainWindow
//MainWindow myMainWindow;
//myMainWindow.show();
//We enter the Qt Event loop here, we don't leave until the MainWindow is closed
//or the console application is terminated.
return app.exec();
}
這可能不關心你,但我認為提起它會很有用。 我自己使用QtSingleApplication
並在QtSingleApplication
經歷了一些奇怪的行為。 QtSingleApplication
似乎並不適用於所有情況。 我在windows中做了這個expierence,但是這取決於Windows特定的bug或QtSingleApplication
的設計QtSingleApplication
,它也可能適用於linux。
根據您啟動應用程序的方式,可以實現多個實例。 當我使用安裝程序對應用程序進行測試時,我獲得了這種體驗。 完成后,安裝程序會自動啟動應用程序。 當我使用桌面鏈接啟動我的應用程序時,我有兩個實例正在運行。 所以QtSingleApplication
的功能似乎取決於應用程序啟動的方式(以及用戶?)。 文檔不清楚這一點。 但我認為,如果沒有另外說明,通常人們會期望這種情況在所有情況下都有效。
因此,如果您不需要QtSingleApplication
添加的額外功能, QSystemSemaphore
或QSharedMemory
似乎是更好的方法。
您的應用程序可以檢查用戶主目錄中是否存在某個文件。 如果存在,則退出應用程序。 如果不存在,則應用程序創建並繼續。 當然,如果用戶一次多次啟動應用程序,您可能會遇到競爭條件。 但對於大多數情況,這個簡單的解決方案應該足夠
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.