From d898efe0e87c2c0102643275903b0864d3783604 Mon Sep 17 00:00:00 2001
From: LightBase Consultoria em Software Publico The QtService component is useful for developing Windows services and Unix daemons. The project provides a QtService template class that can be used to implement service applications, and a QtServiceController class to control a service. On Windows systems the implementation uses the Service Control Manager. On Unix systems services are implemented as daemons. It is a very simple implementation of universal command-line controller. This controller can install and control any service written using QtService component. It demonstrates how to use QtServiceController class. On Windows, this is an alternative to using the "Services" Administrative Tool or the built-in sc.exe command-line tool to control services. A note about services on Windows Vista: Installing/uninstalling and starting/stopping services requires security privileges. The simplest way to achieve this is to set the "Run as Administrator" property on the executable (right-click the executable file, select Properties, and choose the Compatibilty tab in the Properties dialog). This applies even if you are logged in as Administrator. Also, the command-line shell should be started with "Run as Administrator". Note that the service itself does not need special privileges to run. Only if you want the service to be able to install itself (the -i option) or similar, then the service will need to be run as Administrator. Otherwise, the recommended procedure is to use a controller such as this example and/or the "Services" Administrative Tool to manage the service. A usability hint: in some circumstances, e.g. when running this example on Windows Vista with the "Run as Administrator" property set, output will be sent to a shell window which will close immediately upon termination, not leaving the user enough time to read the output. In such cases, append the -w(ait) argument, which will make the controller wait for a keypress before terminating. Here is the complete source code: This example implements a service with a simple user interface. Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. However, although not recommended in the general case, in certain circumstances a service may provide a GUI itself. This is typically only possible if the service process is run as the same user as the one that is logged in, so that it will have access to the screen. Note however that on Windows Vista, service GUIs are not allowed at all, since services run in a diferent session than all user sessions, for security reasons. This example demonstrates how to subclass the QtService class, the use of start(), stop(), pause(), resume(), and how to use processCommand() to receive control commands while running. Here is the complete source code: It is a very simple implementation of a HTTP daemon that listens on chosen port (defaultly 8080) and sends back a simple HTML page back for every GET request it gets. After sending the page, it closes the connection. The server implementation uses the QtService::logMessage() function to send messages and status reports to the system event log. The server also supports a paused state in which case incoming requests are ignored. The HttpService class subclasses QtService to implement the service functionality. The constructor calls the QtService constructor instantiated with QCoreApplication since our service will not use GUI. The first two parameters of our constructor are passed to QtService. The last parameter, "Qt HTTP Daemon", is the name of the service. The implementation of start() first checks if the user passed a port number. If yes that port is used by server to listen on. Otherwise default 8080 port is used. Then creates an instance of the HTTP server using operator new, passing the application object as the parent to ensure that the object gets destroyed. The implementations of pause() and resume() forward the request to the server object. The main entry point function creates the service object and uses the exec() function to execute the service. This is the complete list of members for QtService, including inherited members.
+
+
+ Home
+Service
+
+
+Description
+Classes
+
+
+Examples
+
+
+Tested platforms
+
+
+
+ Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)
+Trademarks
+
+
+
+
+ Home
+A simple Service Controller
+
+ /****************************************************************************
+ **
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+ ** Contact: http://www.qt-project.org/legal
+ **
+ ** This file is part of the Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * Redistributions in binary form must reproduce the above copyright
+ ** notice, this list of conditions and the following disclaimer in
+ ** the documentation and/or other materials provided with the
+ ** distribution.
+ ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ ** the names of its contributors may be used to endorse or promote
+ ** products derived from this software without specific prior written
+ ** permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ****************************************************************************/
+
+ #include <QtCore/QStringList>
+ #include <QtCore/QDir>
+ #include <QtCore/QSettings>
+ #include "qtservice.h"
+
+ int processArgs(int argc, char **argv)
+ {
+ if (argc > 2) {
+ QString arg1(argv[1]);
+ if (arg1 == QLatin1String("-i") ||
+ arg1 == QLatin1String("-install")) {
+ if (argc > 2) {
+ QString account;
+ QString password;
+ QString path(argv[2]);
+ if (argc > 3)
+ account = argv[3];
+ if (argc > 4)
+ password = argv[4];
+ printf("The service %s installed.\n",
+ (QtServiceController::install(path, account, password) ? "was" : "was not"));
+ return 0;
+ }
+ } else {
+ QString serviceName(argv[1]);
+ QtServiceController controller(serviceName);
+ QString option(argv[2]);
+ if (option == QLatin1String("-u") ||
+ option == QLatin1String("-uninstall")) {
+ printf("The service \"%s\" %s uninstalled.\n",
+ controller.serviceName().toLatin1().constData(),
+ (controller.uninstall() ? "was" : "was not"));
+ return 0;
+ } else if (option == QLatin1String("-s") ||
+ option == QLatin1String("-start")) {
+ QStringList args;
+ for (int i = 3; i < argc; ++i)
+ args.append(QString::fromLocal8Bit(argv[i]));
+ printf("The service \"%s\" %s started.\n",
+ controller.serviceName().toLatin1().constData(),
+ (controller.start(args) ? "was" : "was not"));
+ return 0;
+ } else if (option == QLatin1String("-t") ||
+ option == QLatin1String("-terminate")) {
+ printf("The service \"%s\" %s stopped.\n",
+ controller.serviceName().toLatin1().constData(),
+ (controller.stop() ? "was" : "was not"));
+ return 0;
+ } else if (option == QLatin1String("-p") ||
+ option == QLatin1String("-pause")) {
+ printf("The service \"%s\" %s paused.\n",
+ controller.serviceName().toLatin1().constData(),
+ (controller.pause() ? "was" : "was not"));
+ return 0;
+ } else if (option == QLatin1String("-r") ||
+ option == QLatin1String("-resume")) {
+ printf("The service \"%s\" %s resumed.\n",
+ controller.serviceName().toLatin1().constData(),
+ (controller.resume() ? "was" : "was not"));
+ return 0;
+ } else if (option == QLatin1String("-c") ||
+ option == QLatin1String("-command")) {
+ if (argc > 3) {
+ QString codestr(argv[3]);
+ int code = codestr.toInt();
+ printf("The command %s sent to the service \"%s\".\n",
+ (controller.sendCommand(code) ? "was" : "was not"),
+ controller.serviceName().toLatin1().constData());
+ return 0;
+ }
+ } else if (option == QLatin1String("-v") ||
+ option == QLatin1String("-version")) {
+ bool installed = controller.isInstalled();
+ printf("The service\n"
+ "\t\"%s\"\n\n", controller.serviceName().toLatin1().constData());
+ printf("is %s", (installed ? "installed" : "not installed"));
+ printf(" and %s\n\n", (controller.isRunning() ? "running" : "not running"));
+ if (installed) {
+ printf("path: %s\n", controller.serviceFilePath().toLatin1().data());
+ printf("description: %s\n", controller.serviceDescription().toLatin1().data());
+ printf("startup: %s\n", controller.startupType() == QtServiceController::AutoStartup ? "Auto" : "Manual");
+ }
+ return 0;
+ }
+ }
+ }
+ printf("controller [-i PATH | SERVICE_NAME [-v | -u | -s | -t | -p | -r | -c CODE] | -h] [-w]\n\n"
+ "\t-i(nstall) PATH\t: Install the service\n"
+ "\t-v(ersion)\t: Print status of the service\n"
+ "\t-u(ninstall)\t: Uninstall the service\n"
+ "\t-s(tart)\t: Start the service\n"
+ "\t-t(erminate)\t: Stop the service\n"
+ "\t-p(ause)\t: Pause the service\n"
+ "\t-r(esume)\t: Resume the service\n"
+ "\t-c(ommand) CODE\t: Send a command to the service\n"
+ "\t-h(elp)\t\t: Print this help info\n"
+ "\t-w(ait)\t\t: Wait for keypress when done\n");
+ return 0;
+ }
+
+ int main(int argc, char **argv)
+ {
+ #if !defined(Q_OS_WIN)
+ // QtService stores service settings in SystemScope, which normally require root privileges.
+ // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
+ QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
+ qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
+ #endif
+
+ int result = processArgs(argc, argv);
+
+ if (QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-w") ||
+ QString::fromLocal8Bit(argv[argc-1]) == QLatin1String("-wait")) {
+ printf("\nPress Enter to continue...");
+ QFile input;
+ input.open(stdin, QIODevice::ReadOnly);
+ input.readLine();
+ printf("\n");
+ }
+
+ return result;
+ }
+
+ Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)
+Trademarks
+
+
+
+
+ Home
+An Interactive Service
+
+ /****************************************************************************
+ **
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+ ** Contact: http://www.qt-project.org/legal
+ **
+ ** This file is part of the Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * Redistributions in binary form must reproduce the above copyright
+ ** notice, this list of conditions and the following disclaimer in
+ ** the documentation and/or other materials provided with the
+ ** distribution.
+ ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ ** the names of its contributors may be used to endorse or promote
+ ** products derived from this software without specific prior written
+ ** permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ****************************************************************************/
+
+ #include <QtGui/QApplication>
+ #include <QtGui/QDesktopWidget>
+ #include <QtGui/QLabel>
+ #include <QtCore/QDir>
+ #include <QtCore/QSettings>
+ #include "qtservice.h"
+
+ class InteractiveService : public QtService<QApplication>
+ {
+ public:
+ InteractiveService(int argc, char **argv);
+ ~InteractiveService();
+
+ protected:
+
+ void start();
+ void stop();
+ void pause();
+ void resume();
+ void processCommand(int code);
+
+ private:
+ QLabel *gui;
+ };
+
+ InteractiveService::InteractiveService(int argc, char **argv)
+ : QtService<QApplication>(argc, argv, "Qt Interactive Service"), gui(0)
+ {
+ setServiceDescription("A Qt service with user interface.");
+ setServiceFlags(QtServiceBase::CanBeSuspended);
+ }
+
+ InteractiveService::~InteractiveService()
+ {
+ }
+
+ void InteractiveService::start()
+ {
+ #if defined(Q_OS_WIN)
+ if ((QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) &&
+ (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)) {
+ logMessage( "Service GUI not allowed on Windows Vista. See the documentation for this example for more information.", QtServiceBase::Error );
+ return;
+ }
+ #endif
+
+ qApp->setQuitOnLastWindowClosed(false);
+
+ gui = new QLabel("Service", 0, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
+ gui->move(QApplication::desktop()->availableGeometry().topLeft());
+ gui->show();
+ }
+
+ void InteractiveService::stop()
+ {
+ delete gui;
+ }
+
+ void InteractiveService::pause()
+ {
+ if (gui)
+ gui->hide();
+ }
+
+ void InteractiveService::resume()
+ {
+ if (gui)
+ gui->show();
+ }
+
+ void InteractiveService::processCommand(int code)
+ {
+ gui->setText("Command code " + QString::number(code));
+ gui->adjustSize();
+ }
+
+ int main(int argc, char **argv)
+ {
+ #if !defined(Q_OS_WIN)
+ // QtService stores service settings in SystemScope, which normally require root privileges.
+ // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
+ QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
+ qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
+ #endif
+ InteractiveService service(argc, argv);
+ return service.exec();
+ }
+
+ Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)
+Trademarks
+
+
+
+
+ Home
+A simple HTTP Server
+
+ // HttpDaemon is the the class that implements the simple HTTP server.
+ class HttpDaemon : public QTcpServer
+ {
+ Q_OBJECT
+ public:
+ HttpDaemon(quint16 port, QObject* parent = 0)
+ : QTcpServer(parent), disabled(false)
+ {
+ listen(QHostAddress::Any, port);
+ }
+
+ void incomingConnection(int socket)
+ {
+ if (disabled)
+ return;
+
+ // When a new client connects, the server constructs a QTcpSocket and all
+ // communication with the client is done over this QTcpSocket. QTcpSocket
+ // works asynchronously, this means that all the communication is done
+ // in the two slots readClient() and discardClient().
+ QTcpSocket* s = new QTcpSocket(this);
+ connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
+ connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
+ s->setSocketDescriptor(socket);
+
+ QtServiceBase::instance()->logMessage("New Connection");
+ }
+
+ void pause()
+ {
+ disabled = true;
+ }
+
+ void resume()
+ {
+ disabled = false;
+ }
+
+ private slots:
+ void readClient()
+ {
+ if (disabled)
+ return;
+
+ // This slot is called when the client sent data to the server. The
+ // server looks if it was a get request and sends a very simple HTML
+ // document back.
+ QTcpSocket* socket = (QTcpSocket*)sender();
+ if (socket->canReadLine()) {
+ QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
+ if (tokens[0] == "GET") {
+ QTextStream os(socket);
+ os.setAutoDetectUnicode(true);
+ os << "HTTP/1.0 200 Ok\r\n"
+ "Content-Type: text/html; charset=\"utf-8\"\r\n"
+ "\r\n"
+ "<h1>Nothing to see here</h1>\n"
+ << QDateTime::currentDateTime().toString() << "\n";
+ socket->close();
+
+ QtServiceBase::instance()->logMessage("Wrote to client");
+
+ if (socket->state() == QTcpSocket::UnconnectedState) {
+ delete socket;
+ QtServiceBase::instance()->logMessage("Connection closed");
+ }
+ }
+ }
+ }
+ void discardClient()
+ {
+ QTcpSocket* socket = (QTcpSocket*)sender();
+ socket->deleteLater();
+
+ QtServiceBase::instance()->logMessage("Connection closed");
+ }
+
+ private:
+ bool disabled;
+ };
+ class HttpService : public QtService<QCoreApplication>
+ {
+ public:
+ HttpService(int argc, char **argv)
+ : QtService<QCoreApplication>(argc, argv, "Qt HTTP Daemon")
+ {
+ setServiceDescription("A dummy HTTP service implemented with Qt");
+ setServiceFlags(QtServiceBase::CanBeSuspended);
+ }
+ protected:
+ void start()
+ {
+ QCoreApplication *app = application();
+
+ quint16 port = (app->argc() > 1) ?
+ QString::fromLocal8Bit(app->argv()[1]).toUShort() : 8080;
+ daemon = new HttpDaemon(port, app);
+
+ if (!daemon->isListening()) {
+ logMessage(QString("Failed to bind to port %1").arg(daemon->serverPort()), QtServiceBase::Error);
+ app->quit();
+ }
+ }
+ void pause()
+ {
+ daemon->pause();
+ }
+
+ void resume()
+ {
+ daemon->resume();
+ }
+
+ private:
+ HttpDaemon *daemon;
+ };
+ #include "main.moc"
+
+ int main(int argc, char **argv)
+ {
+ #if !defined(Q_OS_WIN)
+ // QtService stores service settings in SystemScope, which normally require root privileges.
+ // To allow testing this example as non-root, we change the directory of the SystemScope settings file.
+ QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
+ qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
+ #endif
+ HttpService service(argc, argv);
+ return service.exec();
+ }
+
+ Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)
+Trademarks
+
+
+
+
+ Home
+List of All Members for QtService
+
+
+
+
+
+
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+
![]() |
+Home | +
The QtService is a convenient template class that allows you to create a service for a particular application type. More...
+#include <QtService>
Inherits QtServiceBase.
+ +QtService ( int argc, char ** argv, const QString & name ) | |
~QtService () |
Application * | application () const |
virtual void | createApplication ( int & argc, char ** argv ) |
virtual int | executeApplication () |
The QtService is a convenient template class that allows you to create a service for a particular application type.
+A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on.
+Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation).
+Note: On Unix systems, this class relies on facilities provided by the QtNetwork module, provided as part of the Qt Open Source Edition and certain Qt Commercial Editions.
+The QtService class functionality is inherited from QtServiceBase, but in addition the QtService class binds an instance of QtServiceBase with an application type.
+Typically, you will create a service by subclassing the QtService template class. For example:
+class MyService : public QtService<QApplication> + { + public: + MyService(int argc, char **argv); + ~MyService(); + + protected: + void start(); + void stop(); + void pause(); + void resume(); + void processCommand(int code); + };+
The application type can be QCoreApplication for services without GUI, QApplication for services with GUI or you can use your own custom application type.
+You must reimplement the QtServiceBase::start() function to perform the service's work. Usually you create some main object on the heap which is the heart of your service.
+In addition, you might want to reimplement the QtServiceBase::pause(), QtServiceBase::processCommand(), QtServiceBase::resume() and QtServiceBase::stop() to intervene the service's process on controller requests. You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented.
+Your custom service is typically instantiated in the application's main function. Then the main function will call your service's exec() function, and return the result of that call. For example:
+int main(int argc, char **argv) + { + MyService service(argc, argv); + return service.exec(); + }+
When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and exit.
+If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.
+See also QtServiceBase and QtServiceController.
+Constructs a QtService object called name. The argc and argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor.
+There can only be one QtService object in a process.
+See also QtServiceBase().
+Destroys the service object.
+Returns a pointer to the application object.
+Reimplemented from QtServiceBase::createApplication().
+Creates application object of type Application passing argc and argv to its constructor.
+Reimplemented from QtServiceBase::executeApplication().
+Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+
![]() |
+Home | +
This is the complete list of members for QtServiceBase, including inherited members.
+
|
|
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+
![]() |
+Home | +
The QtServiceBase class provides an API for implementing Windows services and Unix daemons. More...
+#include <QtServiceBase>
Inherited by QtService.
+ +enum | MessageType { Success, Error, Warning, Information } |
enum | ServiceFlag { Default, CanBeSuspended, CannotBeStopped, NeedsStopOnShutdown } |
flags | ServiceFlags |
QtServiceBase ( int argc, char ** argv, const QString & name ) | |
virtual | ~QtServiceBase () |
int | exec () |
void | logMessage ( const QString & message, MessageType type = Success, int id = 0, uint category = 0, const QByteArray & data = QByteArray() ) |
QString | serviceDescription () const |
ServiceFlags | serviceFlags () const |
QString | serviceName () const |
void | setServiceDescription ( const QString & description ) |
void | setServiceFlags ( ServiceFlags flags ) |
void | setStartupType ( QtServiceController::StartupType type ) |
QtServiceController::StartupType | startupType () const |
QtServiceBase * | instance () |
virtual void | createApplication ( int & argc, char ** argv ) = 0 |
virtual int | executeApplication () = 0 |
virtual void | pause () |
virtual void | processCommand ( int code ) |
virtual void | resume () |
virtual void | start () = 0 |
virtual void | stop () |
The QtServiceBase class provides an API for implementing Windows services and Unix daemons.
+A Windows service or Unix daemon (a "service"), is a program that runs "in the background" independently of whether a user is logged in or not. A service is often set up to start when the machine boots up, and will typically run continuously as long as the machine is on.
+Services are usually non-interactive console applications. User interaction, if required, is usually implemented in a separate, normal GUI application that communicates with the service through an IPC channel. For simple communication, QtServiceController::sendCommand() and QtService::processCommand() may be used, possibly in combination with a shared settings file. For more complex, interactive communication, a custom IPC channel should be used, e.g. based on Qt's networking classes. (In certain circumstances, a service may provide a GUI itself, ref. the "interactive" example documentation).
+Typically, you will create a service by subclassing the QtService template class which inherits QtServiceBase and allows you to create a service for a particular application type.
+The Windows implementation uses the NT Service Control Manager, and the application can be controlled through the system administration tools. Services are usually launched using the system account, which requires that all DLLs that the service executable depends on (i.e. Qt), are located in the same directory as the service, or in a system path.
+On Unix a service is implemented as a daemon.
+You can retrieve the service's description, state, and startup type using the serviceDescription(), serviceFlags() and startupType() functions respectively. The service's state is decribed by the ServiceFlag enum. The mentioned properites can also be set using the corresponding set functions. In addition you can retrieve the service's name using the serviceName() function.
+Several of QtServiceBase's protected functions are called on requests from the QtServiceController class:
+You can control any given service using an instance of the QtServiceController class which also allows you to control services from separate applications. The mentioned functions are all virtual and won't do anything unless they are reimplemented. You can reimplement these functions to pause and resume the service's execution, as well as process user commands and perform additional clean-ups before shutting down.
+QtServiceBase also provides the static instance() function which returns a pointer to an application's QtServiceBase instance. In addition, a service can report events to the system's event log using the logMessage() function. The MessageType enum describes the different types of messages a service reports.
+The implementation of a service application's main function typically creates an service object derived by subclassing the QtService template class. Then the main function will call this service's exec() function, and return the result of that call. For example:
+int main(int argc, char **argv) + { + MyService service(argc, argv); + return service.exec(); + }+
When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and return.
+The following arguments are recognized as service specific:
+Short | Long | Explanation |
---|---|---|
-i | -install | Install the service. |
-u | -uninstall | Uninstall the service. |
-e | -exec | Execute the service as a standalone application (useful for debug purposes). This is a blocking call, the service will be executed like a normal application. In this mode you will not be able to communicate with the service from the contoller. |
-t | -terminate | Stop the service. |
-p | -pause | Pause the service. |
-r | -resume | Resume a paused service. |
-c cmd | -command cmd | Send the user defined command code cmd to the service application. |
-v | -version | Display version and status information. |
If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.
+See also QtService and QtServiceController.
+This enum describes the different types of messages a service reports to the system log.
+Constant | Value | Description |
---|---|---|
QtServiceBase::Success | 0 | An operation has succeeded, e.g. the service is started. |
QtServiceBase::Error | 1 | An operation failed, e.g. the service failed to start. |
QtServiceBase::Warning | 2 | An operation caused a warning that might require user interaction. |
QtServiceBase::Information | 3 | Any type of usually non-critical information. |
This enum describes the different capabilities of a service.
+Constant | Value | Description |
---|---|---|
QtServiceBase::Default | 0x00 | The service can be stopped, but not suspended. |
QtServiceBase::CanBeSuspended | 0x01 | The service can be suspended. |
QtServiceBase::CannotBeStopped | 0x02 | The service cannot be stopped. |
QtServiceBase::NeedsStopOnShutdown | 0x04 | (Windows only) The service will be stopped before the system shuts down. Note that Microsoft recommends this only for services that must absolutely clean up during shutdown, because there is a limited time available for shutdown of services. |
The ServiceFlags type is a typedef for QFlags<ServiceFlag>. It stores an OR combination of ServiceFlag values.
+Creates a service instance called name. The argc and argv parameters are parsed after the exec() function has been called. Then they are passed to the application's constructor. The application type is determined by the QtService subclass.
+The service is neither installed nor started. The name must not contain any backslashes or be longer than 255 characters. In addition, the name must be unique in the system's service database.
+See also exec(), start(), and QtServiceController::install().
+Destroys the service object. This neither stops nor uninstalls the service.
+To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the QtServiceController::uninstall() function.
+See also stop() and QtServiceController::uninstall().
+Creates the application object using the argc and argv parameters.
+This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() before it calls the executeApplication() and start() functions.
+The createApplication() function is implemented in QtService, but you might want to reimplement it, for example, if the chosen application type's constructor needs additional arguments.
+See also exec() and QtService.
+Executes the service.
+When the exec() function is called, it will parse the service specific arguments passed in argv, perform the required actions, and exit.
+If none of the arguments is recognized as service specific, exec() will first call the createApplication() function, then executeApplication() and finally the start() function. In the end, exec() returns while the service continues in its own process waiting for commands from the service controller.
+See also QtServiceController.
+Executes the application previously created with the createApplication() function.
+This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() after it has called the createApplication() function and before start() function.
+This function is implemented in QtService.
+See also exec() and createApplication().
+Returns a pointer to the current application's QtServiceBase instance.
+Reports a message of the given type with the given message to the local system event log. The message identifier id and the message category are user defined values. The data parameter can contain arbitrary binary data.
+Message strings for id and category must be provided by a message file, which must be registered in the system registry. Refer to the MSDN for more information about how to do this on Windows.
+See also MessageType.
+Reimplement this function to pause the service's execution (for example to stop a polling timer, or to ignore socket notifiers).
+This function is called in reply to controller requests. The default implementation does nothing.
+See also resume() and QtServiceController::pause().
+Reimplement this function to process the user command code.
+This function is called in reply to controller requests. The default implementation does nothing.
+See also QtServiceController::sendCommand().
+Reimplement this function to continue the service after a call to pause().
+This function is called in reply to controller requests. The default implementation does nothing.
+See also pause() and QtServiceController::resume().
+Returns the description of the service.
+See also setServiceDescription() and serviceName().
+Returns the service's state which is decribed using the ServiceFlag enum.
+See also ServiceFlags and setServiceFlags().
+Returns the name of the service.
+See also QtServiceBase() and serviceDescription().
+Sets the description of the service to the given description.
+See also serviceDescription().
+Sets the service's state to the state described by the given flags.
+See also ServiceFlags and serviceFlags().
+Sets the service's startup type to the given type.
+See also QtServiceController::StartupType and startupType().
+This function must be implemented in QtServiceBase subclasses in order to perform the service's work. Usually you create some main object on the heap which is the heart of your service.
+The function is only called when no service specific arguments were passed to the service constructor, and is called by exec() after it has called the executeApplication() function.
+Note that you don't need to create an application object or call its exec() function explicitly.
+See also exec(), stop(), and QtServiceController::start().
+Returns the service's startup type.
+See also QtServiceController::StartupType and setStartupType().
+Reimplement this function to perform additional cleanups before shutting down (for example deleting a main object if it was created in the start() function).
+This function is called in reply to controller requests. The default implementation does nothing.
+See also start() and QtServiceController::stop().
+Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+
![]() |
+Home | +
This is the complete list of members for QtServiceController, including inherited members.
+
|
|
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+
![]() |
+Home | +
The QtServiceController class allows you to control services from separate applications. More...
+#include <QtServiceController>+
enum | StartupType { AutoStartup, ManualStartup } |
QtServiceController ( const QString & name ) | |
virtual | ~QtServiceController () |
bool | isInstalled () const |
bool | isRunning () const |
bool | pause () |
bool | resume () |
bool | sendCommand ( int code ) |
QString | serviceDescription () const |
QString | serviceFilePath () const |
QString | serviceName () const |
bool | start ( const QStringList & arguments ) |
bool | start () |
StartupType | startupType () const |
bool | stop () |
bool | uninstall () |
bool | install ( const QString & serviceFilePath, const QString & account = QString(), const QString & password = QString() ) |
The QtServiceController class allows you to control services from separate applications.
+QtServiceController provides a collection of functions that lets you install and run a service controlling its execution, as well as query its status.
+In order to run a service, the service must be installed in the system's service database using the install() function. The system will start the service depending on the specified StartupType; it can either be started during system startup, or when a process starts it manually.
+Once a service is installed, the service can be run and controlled manually using the start(), stop(), pause(), resume() or sendCommand() functions. You can at any time query for the service's status using the isInstalled() and isRunning() functions, or you can query its properties using the serviceDescription(), serviceFilePath(), serviceName() and startupType() functions. For example:
+MyService service; \\ which inherits QtService + QString serviceFilePath; + + QtServiceController controller(service.serviceName()); + + if (controller.install(serviceFilePath)) + controller.start() + + if (controller.isRunning()) + QMessageBox::information(this, tr("Service Status"), + tr("The %1 service is started").arg(controller.serviceName())); + + ... + + controller.stop(); + controller.uninstall(); + }+
An instance of the service controller can only control one single service. To control several services within one application, you must create en equal number of service controllers.
+The QtServiceController destructor neither stops nor uninstalls the associated service. To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function.
+See also QtServiceBase and QtService.
+This enum describes when a service should be started.
+Constant | Value | Description |
---|---|---|
QtServiceController::AutoStartup | 0 | The service is started during system startup. |
QtServiceController::ManualStartup | 1 | The service must be started manually by a process. |
Warning: The StartupType enum is ignored under UNIX-like systems. A service, or daemon, can only be started manually on such systems with current implementation.
+See also startupType().
+Creates a controller object for the service with the given name.
+Destroys the service controller. This neither stops nor uninstalls the controlled service.
+To stop a service the stop() function must be called explicitly. To uninstall a service, you can use the uninstall() function.
+See also stop() and QtServiceController::uninstall().
+Installs the service with the given serviceFilePath and returns true if the service is installed successfully; otherwise returns false.
+On Windows service is installed in the system's service control manager with the given account and password.
+On Unix service configuration is written to QSettings::SystemScope using "QtSoftware" as organization name. account and password arguments are ignored.
+Warning: Due to the different implementations of how services (daemons) are installed on various UNIX-like systems, this method doesn't integrate the service into the system's startup scripts.
+See also uninstall() and start().
+Returns true if the service is installed; otherwise returns false.
+On Windows it uses the system's service control manager.
+On Unix it checks configuration written to QSettings::SystemScope using "QtSoftware" as organization name.
+See also install().
+Returns true if the service is running; otherwise returns false. A service must be installed before it can be run using a controller.
+See also start() and isInstalled().
+Requests the running service to pause. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::pause() implementation. The function does nothing if the service is not running.
+Returns true if a running service was successfully paused; otherwise returns false.
+See also resume(), QtServiceBase::pause(), and QtServiceBase::ServiceFlags.
+Requests the running service to continue. If the service's state is QtServiceBase::CanBeSuspended, the service will call the QtServiceBase::resume() implementation. This function does nothing if the service is not running.
+Returns true if a running service was successfully resumed; otherwise returns false.
+See also pause(), QtServiceBase::resume(), and QtServiceBase::ServiceFlags.
+Sends the user command code to the service. The service will call the QtServiceBase::processCommand() implementation. This function does nothing if the service is not running.
+Returns true if the request was sent to a running service; otherwise returns false.
+See also QtServiceBase::processCommand().
+Returns the description of the controlled service.
+See also install() and serviceName().
+Returns the file path to the controlled service.
+See also install() and serviceName().
+Returns the name of the controlled service.
+See also QtServiceController() and serviceDescription().
+Starts the installed service passing the given arguments to the service. A service must be installed before a controller can run it.
+Returns true if the service could be started; otherwise returns false.
+See also install() and stop().
+This is an overloaded function.
+Starts the installed service without passing any arguments to the service.
+Returns the startup type of the controlled service.
+See also install() and serviceName().
+Requests the running service to stop. The service will call the QtServiceBase::stop() implementation unless the service's state is QtServiceBase::CannotBeStopped. This function does nothing if the service is not running.
+Returns true if a running service was successfully stopped; otherwise false.
+See also start(), QtServiceBase::stop(), and QtServiceBase::ServiceFlags.
+Uninstalls the service and returns true if successful; otherwise returns false.
+On Windows service is uninstalled using the system's service control manager.
+On Unix service configuration is cleared using QSettings::SystemScope with "QtSoftware" as organization name.
+See also install().
+Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) | +Trademarks | +Qt Solutions |
+