summaryrefslogtreecommitdiffstats
path: root/qtsingleapplication/examples/console/main.cpp
blob: 13fd00e2f663f0c9b20559722a1e972e1c709535 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
// SPDX-License-Identifier: BSD-3-Clause


#include "qtsinglecoreapplication.h"
#include <QDebug>


void report(const QString& msg)
{
    qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg));
}

class MainClass : public QObject
{
    Q_OBJECT
public:
    MainClass()
        : QObject()
        {}

public slots:
    void handleMessage(const QString& message)
        {
            report( "Message received: \"" + message + "\"");
        }
};

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();
    }
}


#include "main.moc"