Windows服务如何确定它的服务名称? [英] How can a Windows Service determine its ServiceName?

查看:162
本文介绍了Windows服务如何确定它的服务名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了,但没有找到什么应该是一个简单的问题:

I've looked and couldn't find what should be a simple question:

如何可以在Windows服务决定它启动的服务名称?

我知道安装可以在注册表破解并添加命令行参数,但逻辑上这似乎是它的的是不必要的,因此这个问题。

I know the installation can hack at the registry and add a command line argument, but logically that seems like it should be unnecessary, hence this question.

我希望能比注册表破解更干净运行单个二进制文件的多个副本。

I'm hoping to run multiple copies of a single binary more cleanly than the registry hack.

修改

这是用C#。我的应用程序的的Main()的切入点,做不同的事情,这取决于
命令行参数:

This is written in C#. My apps Main() entry point does different things, depending on command line arguments:


  • 安装或卸载该服务。命令行可以提供一个非默认
    服务名称并能改变工作线程的数量。

  • (调试)运行作为命令行可执行文件,

  • 运行作为Windows服务。在这里,它创造了我的 ServiceBase 的衍生实例
    类,然后调用的 System.ServiceProcess.ServiceBase.Run(实例);

  • Install or Uninstall the service. The command line can provide a non-default ServiceName and can change the number of worker threads.
  • Run as a command-line executable (for debugging),
  • Run as a "Windows Service". Here, it creates an instance of my ServiceBase-derived class, then calls System.ServiceProcess.ServiceBase.Run(instance);

目前,安装一步附加的服务名称和线程数到的的ImagePath 的注册表,以便应用程序能确定它的服务名称。

Currently, the installation step appends the service name and thread count to the ImagePath in the registry so the app can determine it's ServiceName.

推荐答案

从:<一href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024

下面是一个WMI的解决方案。重写的 ServiceBase.ServiceMainCallback()的也可以工作,但是这似乎为我工作...

Here is a WMI solution. Overriding the ServiceBase.ServiceMainCallback() might also work, but this seems to work for me...

    protected String GetServiceName()
    {
        // Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns
        // an empty string,
        // see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024

        // So we have to do some more work to find out our service name, this only works if
        // the process contains a single service, if there are more than one services hosted
        // in the process you will have to do something else

        int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
        String query = "SELECT * FROM Win32_Service where ProcessId = " + processId;
        System.Management.ManagementObjectSearcher searcher =
            new System.Management.ManagementObjectSearcher(query);

        foreach (System.Management.ManagementObject queryObj in searcher.Get()) {
            return queryObj["Name"].ToString();
        }

        throw new Exception("Can not get the ServiceName");
    }

这篇关于Windows服务如何确定它的服务名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆