Reputation: 665
I have server programm that works fine, listening incoming clients. Hence, I would like to prevent it from duplicate lauch, as I want only the one server to make a service for connected entities, if it's possible?
Upvotes: 0
Views: 404
Reputation: 6295
You can lock a specific file using lockForWriting
method of QReadWriteLock and keep it locked as long as the application is running and if you can't lock it, exit the application. Since only one instance will be able to lock the file for writing, other instances will terminate themselves.
Upvotes: 2
Reputation: 4025
You can use synchronization primitives.
For example: named mutex.
When an application is started it check whether mutex with the given name exists if so it notifies user that only one instance is allowed and it is already running, if not so - application starts
Upvotes: 0
Reputation: 3934
I am using QSingleApplication - and it is wroking great.
Source code:
Example code from there:
int main(int argc, char **argv)
{
report("Starting up");
QtSingleCoreApplication app(argc, argv);
if (app.isRunning()) {
QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid()));
bool sentok = app.sendMessage(msg, 2000);
QString rep("Another instance is running, so I will exit.");
rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen.";
report(rep);
return 0;
} else {
report("No other instance is running; so I will.");
MainClass mainObj;
QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
&mainObj, SLOT(handleMessage(const QString&)));
return app.exec();
}
}
Upvotes: 0