如何强制我的应用程序只打开一个exe?qt,linux

dev*_*dev 11 c++ linux qt mutex process

我希望我的应用程序只打开一个进程,即如果一个进程已经打开并且用户想要再次打开exe - 它将不会打开另一个进程.

我怎么能在Qt-linux中做到这一点?

10倍!

ere*_*eOn 23

你在寻找什么QtSingleApplication.

如果您启动应用程序的另一个实例,第一个实例甚至会得到通知(您可以传递您想要的任何数据结构).

每当启动另一个实例时,我就用它将现有应用程序带到前面.

  • @JimInTexas:没有冒犯,但OP只想要一种方法来防止同一个用户启动他自己的应用程序的几个进程.为此目的,`QtSingleApplication`正好**他所需要的.现在也许它不适合你的**特定用例,但这与问题无关.通常,答案会因为错误而被低估,而就这个问题而言,情况并非如此.是吗 ? (5认同)

Eti*_*ard 15

在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();
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为太脆弱了 - 如果应用程序崩溃,它会使sharedmem段落后,你无法重启进程."但如果最后一个线程或进程在没有运行QSharedMemory析构函数的情况下崩溃,那么共享内存段将在崩溃中幸存下来." (QSharedMemory docs) (3认同)

bew*_*bew 0

您的应用程序可以检查用户主目录中是否存在某个文件。如果存在,则应用程序退出。如果不存在,应用程序将创建它并继续。当然,如果用户一次多次启动应用程序,您可能会遇到竞争条件。但对于大多数情况,这个简单的解决方案应该足够了。