Skip to content

Instantly share code, notes, and snippets.

@ndtimofeev
Created June 12, 2016 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndtimofeev/0a6a4e04b5b0c9f3aee17bae24b78db4 to your computer and use it in GitHub Desktop.
Save ndtimofeev/0a6a4e04b5b0c9f3aee17bae24b78db4 to your computer and use it in GitHub Desktop.
// 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