Created
June 12, 2016 09:48
-
-
Save ndtimofeev/0a6a4e04b5b0c9f3aee17bae24b78db4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// core | |
#include <QObject> | |
#include <QTimer> | |
#include <QDebug> | |
// network | |
#include <QLocalSocket> | |
#include <QLocalServer> | |
// widgets | |
#include <QApplication> | |
// POSIX | |
#include <signal.h> | |
#include <unistd.h> | |
void catchUnixSignals(const std::vector<int>& quitSignals, | |
const std::vector<int>& ignoreSignals = std::vector<int>()) { | |
auto handler = [](int sig) ->void { | |
printf("\nquit the application (user request signal = %d).\n", sig); | |
QCoreApplication::quit(); | |
}; | |
// all these signals will be ignored. | |
for ( int sig : ignoreSignals ) | |
signal(sig, SIG_IGN); | |
// each of these signals calls the handler (quits the QCoreApplication). | |
for ( int sig : quitSignals ) | |
signal(sig, handler); | |
} | |
int main( int argc, char** argv ) | |
{ | |
QApplication app( argc, argv ); | |
catchUnixSignals({ SIGQUIT, SIGINT, SIGTERM, SIGHUP }); | |
QLocalServer ipc; | |
if ( ipc.listen( "/tmp/ipc" ) ) | |
{ | |
QObject::connect( &ipc, &QLocalServer::newConnection, | |
[&]() | |
{ | |
auto socket = ipc.nextPendingConnection(); | |
QObject::connect( socket, &QIODevice::readyRead, | |
[socket]() | |
{ | |
QDataStream stream( socket ); | |
QList<QString> args; | |
stream >> args; | |
qDebug() << args; | |
} ); | |
} ); | |
} | |
else | |
{ | |
if ( ipc.serverError() == QAbstractSocket::AddressInUseError ) | |
{ | |
QTimer::singleShot( 0, | |
[&]() | |
{ | |
QLocalSocket* socket = new QLocalSocket( &app ); | |
socket->connectToServer( "/tmp/ipc", QIODevice::WriteOnly ); | |
if ( socket->waitForConnected( 1000 ) ) | |
{ | |
QDataStream input( socket ); | |
QList<QString> args = QCoreApplication::arguments(); | |
input << args; | |
socket->waitForBytesWritten( 30000 ); | |
socket->flush(); | |
QCoreApplication::quit(); | |
} | |
else | |
QCoreApplication::exit( -1 ); | |
} ); | |
} | |
} | |
return app.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment