Search code examples
c++linuxdaemonbackground-process

How to control a background-process/daemon


I'm currently trying to create a program in C++ for Linux and I'm quite new to it.The program should do its stuff(Network communication and calculations) in the background and could be controlled with commands from the terminal, like "prog -start", "prog -stop", "prog -limitUp 1000".

My idea to realize that was to create the program as a daemon to always run in the background. To control the whole thing I thought to setup a linux command that takes the given arguments to the main function of my program and tries to reconnect to the daemon in the background to execute the given command then.

What is the best way to achieve such functionality (i.e. a daemon listening in the background and a client/command that can be used to control it).


Solution

  • Here is an example program built with C++/Qt. As you can see, the process starts as daemon if no arguments are given, listening to a named local socket.

    If arguments are given, it connects to that local socket, and sends its arguments. The daemon then prints them.

    #include <QCoreApplication>
    #include <QLocalServer>
    #include <QLocalSocket>
    #include <QStringList>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        if (a.arguments().size() == 1) {
            // Act as a server.
            QLocalServer server;
            server.listen("MyDaemon");
            while (server.waitForNewConnection(-1)) {
                QLocalSocket *socket = server.nextPendingConnection();
                socket->waitForReadyRead();
                qDebug() << "received message" << socket->readAll();
                delete socket;
            }
        } else {
            // Act as a client.
            QLocalSocket socket;
            socket.connectToServer("MyDaemon");
            socket.waitForConnected();
            socket.write(a.arguments().join(' ').toUtf8() + "\n");
            socket.waitForBytesWritten();
        }
    
        return 0;
    }
    

    enter image description here