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

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

问题描述

我已经看过了,但找不到一个应该是简单的问题:

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

Windows 服务如何确定为其启动的 ServiceName?

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

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:

  • 安装或卸载服务.命令行可以提供一个非默认的ServiceName 并且可以更改工作线程的数量.
  • 作为命令行可执行文件运行(用于调试),
  • 作为Windows 服务"运行.在这里,它创建了我的 ServiceBase 派生的实例类,然后调用System.ServiceProcess.ServiceBase.Run(instance);
  • 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,以便应用程序可以确定它的 ServiceName.

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.

推荐答案

来自: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天全站免登陆