简体   繁体   English

QtService不会通过Service Manager窗口传递启动参数

[英]QtService does not pass the start parameters from Service Manager window

How to get the Start parameters that are passed from the Windows Service Manager dialog. 如何获取从Windows服务管理器对话框传递的开始参数。 I was hoping I would get them as command line args passed to the main function. 我希望将它们作为命令行参数传递给main函数。

在此处输入图片说明

If I pass the arguments to binPath when creating the service then I get the arguments passed into main function. 如果我在创建服务时将参数传递给binPath,那么我会将参数传递给main函数。

sc create "Myservice" binPath= "Path_to_exe\Myservice.exe -port 18082"

But this way we need to uninstall and install the service everytime to change any arguments. 但是通过这种方式,我们需要每次都卸载并安装服务以更改任何参数。 Is there any way to get the start parameters in Qt? 有什么方法可以在Qt中获取启动参数吗?

If I create the service using .NET, I can use the following function to get these Start parameters. 如果使用.NET创建服务,则可以使用以下函数获取这些Start参数。

 System::Environment::GetCommandLineArgs();

I know that this question is old, but how it keeps unanswered and the problem persist until nowadays, I believe that is appropriate give a possible answer. 我知道这个问题很久了,但是如何解决却一直没有解决,直到今天,这个问题仍然存在,我认为应该给出一个可能的答案。

You will be able to get the start parameters of a Qt Service by reimplementing void QtServiceBase::createApplication ( int & argc, char ** argv ) 通过重新实现void QtServiceBase::createApplication ( int & argc, char ** argv )您将可以获得Qt服务的启动参数。

According to the docs : 根据文档

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.

So when your service call the start function the args will be available, because the createApplication is called before the start function. 因此,当您的服务调用start函数时,args将可用,因为createApplicationstart函数之前被调用。

Here a example: 这里有个例子:

#include <QtCore>
#include "qtservice.h"

class Service : public QtService<QCoreApplication>
{
public:
    explicit Service(int argc, char *argv[], const QString &name) : QtService<QCoreApplication>(argc, argv, name)
    {
        setServiceDescription("Service");
        setServiceFlags(QtServiceBase::CanBeSuspended);
        setStartupType(QtServiceController::ManualStartup);
    }

protected:
    void start()
    {
        // use args;
    }

    void stop()
    {
    }

    void pause()
    {
    }

    void resume()
    {
    }

    void processCommand(int code)
    {
    }

    void createApplication(int &argc, char **argv)
    {
        for (int i = 0; i < argc; i++)
            args.append(QString(argv[i]));

        QtService::createApplication(argc, argv);
    }
private:
    QStringList args;
};


int main(int argc, char *argv[])
{
    Service s(argc, argv, "Service");
    return s.exec();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM