Qt Excellent Open Source Project Eighteen: QtService

QtService is an open source project github address for implementing Windows services or unix daemons
: https://github.com/qtproject/qt-solutions/tree/master/qtservice
The source code can be compiled into a dynamic library or directly in the project Citing the source code The source
code directory qtservice/examples contains three examples, which are worth referring to

1. Trial

1. Create a new console program TestServer2

Then copy the qtservice source code to the project

Refer to the example qtservice/examples/server to write the simplest Windows service

#include <QCoreApplication>
#include <QDebug>

#include "qtservice.h"

class TestService2 : public QtService<QCoreApplication>
    TestService2(int argc, char **argv) : QtService<QCoreApplication>(argc, argv, "TestService2")
        setServiceDescription("TestService2 cao shang pa");


    void start()override

        // 将服务要做的事情放在这里.
        qDebug() << Q_FUNC_INFO;
    void stop()override
        qDebug() << Q_FUNC_INFO;
    void pause()override

    void resume()override


int main(int argc, char *argv[])
    TestService2 service(argc, argv);
    return service.exec();

The pro file is as follows

QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle




Such a Windows service program is completed, isn't it super simple.

2. Add source code references in the project file pro


3. run

Start the cmd window with administrator privileges, cd to TestService2/out, and execute:

TestService2.exe -h

output basic usage

①Installation service

TestService2.exe -i

At this time, you can see the installed service in the "Computer Management" window, but the service is not running at this time

② Start the service


Just do this directly, without parameters, and the service shows that it is running at this time

③Stop service

TestService2.exe -t

④ Uninstall service

TestService2.exe -u

Other parameters can be tried by yourself

PS: If you want to control the service in the code, refer to this example qtservice/examples/controller

2. Principle

I shared the creation of Windows system services in C++ before . The implementation of QtServer on Windows is actually the WIndows API called, as shown in the figure below

In fact, the underlying principles of all third-party libraries are the same. They are all called system APIs. Those that can stand out must have simple interfaces and excellent performance. QtServer not only simplifies complex work, but also humanizes it—when TestService2.exe -e is executed, TestService2.exe is an ordinary Qt application, and the debugging information in the start function can be directly printed to the console. You don't need to use DebugView to capture debugging information like in C++ to create Windows system services

Original link: https://blog.csdn.net/caoshangpa/article/details/130276690

Guess you like

Origin blog.csdn.net/caoshangpa/article/details/130276690