找出Windows服务正在运行的进程名称.NET 1.1

发布于 2024-07-13 11:39:02 字数 88 浏览 6 评论 0原文

我们正在使用一个写得很糟糕的 Windows 服务,当我们试图从代码中阻止它时,它会挂起。 因此,我们需要找到与该服务相关的进程并将其杀死。 有什么建议么?

We are using a badly written windows service, which will hang when we are trying to Stop it from code. So we need to find which process is related to that service and kill it.
Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

顾北清歌寒 2024-07-20 11:39:02

您可以使用 System.Management.MangementObjectSearcher 获取服务的进程 ID 和 System.Diagnostics.Process 获取相应的 Process 实例并杀死它。

以下程序中的 KillService() 方法显示了如何执行此操作:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Management;

namespace KillProcessApp {
    class Program {
        static void Main(string[] args) {
            KillService("YourServiceName");
        }

        static void KillService(string serviceName) {
            string query = string.Format(
                "SELECT ProcessId FROM Win32_Service WHERE Name='{0}'", 
                serviceName);
            ManagementObjectSearcher searcher = 
                new ManagementObjectSearcher(query);
            foreach (ManagementObject obj in searcher.Get()) {
                uint processId = (uint) obj["ProcessId"];
                Process process = null;
                try
                {
                    process = Process.GetProcessById((int)processId);
                }
                catch (ArgumentException)
                {
                    // Thrown if the process specified by processId
                    // is no longer running.
                }
                try
                {
                    if (process != null) 
                    {
                        process.Kill();
                    }
                }
                catch (Win32Exception)
                {
                    // Thrown if process is already terminating,
                    // the process is a Win16 exe or the process
                    // could not be terminated.
                }
                catch (InvalidOperationException)
                {
                    // Thrown if the process has already terminated.
                }
            }
        }
    }
}

You can use System.Management.MangementObjectSearcher to get the process ID of a service and System.Diagnostics.Process to get the corresponding Process instance and kill it.

The KillService() method in the following program shows how to do this:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Management;

namespace KillProcessApp {
    class Program {
        static void Main(string[] args) {
            KillService("YourServiceName");
        }

        static void KillService(string serviceName) {
            string query = string.Format(
                "SELECT ProcessId FROM Win32_Service WHERE Name='{0}'", 
                serviceName);
            ManagementObjectSearcher searcher = 
                new ManagementObjectSearcher(query);
            foreach (ManagementObject obj in searcher.Get()) {
                uint processId = (uint) obj["ProcessId"];
                Process process = null;
                try
                {
                    process = Process.GetProcessById((int)processId);
                }
                catch (ArgumentException)
                {
                    // Thrown if the process specified by processId
                    // is no longer running.
                }
                try
                {
                    if (process != null) 
                    {
                        process.Kill();
                    }
                }
                catch (Win32Exception)
                {
                    // Thrown if process is already terminating,
                    // the process is a Win16 exe or the process
                    // could not be terminated.
                }
                catch (InvalidOperationException)
                {
                    // Thrown if the process has already terminated.
                }
            }
        }
    }
}
陌伤ぢ 2024-07-20 11:39:02

WMI 有以下信息:Win32_Service 类。

像使用 System.Management 这样的 WQL 查询

SELECT ProcessId FROM Win32_Service WHERE Name='MyServiceName'

应该可以解决问题。

快速查看一下:taskllist.exe /svc 以及命令行中的其他工具。

WMI has this information: the Win32_Service class.

A WQL query like

SELECT ProcessId FROM Win32_Service WHERE Name='MyServiceName'

using System.Management should do the trick.

From a quick look see: taskllist.exe /svc and other tools from the command line.

如果没有你 2024-07-20 11:39:02

您可以使用

tasklist /svc /fi "SERVICES eq YourServiceName"

查找进程名称和 ID,以及同一进程是否托管其他服务。

You can use

tasklist /svc /fi "SERVICES eq YourServiceName"

To find the process name and id, and also if the same process hosts other services.

喵星人汪星人 2024-07-20 11:39:02

要准确回答我的问题 - 如何找到与某些服务相关的进程:

ManagementObjectSearcher searcher = new ManagementObjectSearcher
  ("SELECT * FROM Win32_Service WHERE DisplayName = '" + serviceName + "'");

foreach( ManagementObject result in searcher.Get() )
{
  if (result["DisplayName"].ToString().ToLower().Equals(serviceName.ToLower()))
  {
    int iPID = Convert.ToInt32( result["ProcessId"] );
    KillProcessByID(iPID, 1000); //some method that will kill Process for given PID and timeout. this should be trivial
  }
}

}

To answer exactly to my question - how to find Process related to some service:

ManagementObjectSearcher searcher = new ManagementObjectSearcher
  ("SELECT * FROM Win32_Service WHERE DisplayName = '" + serviceName + "'");

foreach( ManagementObject result in searcher.Get() )
{
  if (result["DisplayName"].ToString().ToLower().Equals(serviceName.ToLower()))
  {
    int iPID = Convert.ToInt32( result["ProcessId"] );
    KillProcessByID(iPID, 1000); //some method that will kill Process for given PID and timeout. this should be trivial
  }
}

}

冰火雁神 2024-07-20 11:39:02

Microsoft/SysInternals 有一个名为 PsKill 的命令行工具,它允许您按名称终止进程。 该工具还允许您终止其他服务器上的进程。 Windows SysInternals

用法: pskill [-t] [\computer [-u 用户名 [-p 密码]]] <进程 ID | 名称>
   -t  终止进程及其后代。
   -u  指定用于登录远程计算机的可选用户名。
  -p  指定用户名的可选密码。 如果您省略此项,系统将提示您输入隐藏密码。

Microsoft/SysInternals has a command-line tool called PsKill that allows you to kill a process by name. This tool also allows you to kill processes on other servers. Windows SysInternals

Usage: pskill [-t] [\computer [-u username [-p password]]] <process ID | name>
   -t  Kill the process and its descendants.
   -u  Specifies optional user name for login to remote computer.
   -p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.

我一直都在从未离去 2024-07-20 11:39:02

我想这是一个两步过程 - 如果它始终是相同的服务,您可以使用其他答案中建议的方法轻松找到进程名称。

然后,我在 .NET 1.1 Web 服务器上的类中包含以下代码:

Process[] runningProcs = 
          Process.GetProcessesByName("ProcessName");

foreach (Process runningProc in runningProcs)
{
    // NOTE: Kill only works for local processes
    runningProc.Kill();
}

Kill 方法 可能会抛出一些您应该考虑捕获的异常 - 特别是 Win32Exception,如果进程无法被终止,则会抛出该异常。

请注意 WaitForExit 方法HasExited 属性也存在于 1.1 世界中,但是1.1 中的 Kill 文档页面中没有提及。

I guess it's a two step process - if it's always the same service, you can easily find the process name using methods suggested in other answers.

I then have the following code in a class on a .NET 1.1 web server:

Process[] runningProcs = 
          Process.GetProcessesByName("ProcessName");

foreach (Process runningProc in runningProcs)
{
    // NOTE: Kill only works for local processes
    runningProc.Kill();
}

The Kill method can throw a few exceptions that you should consider catching - especially the Win32Exception, that is thrown if the process cannot be killed.

Note that the WaitForExit method and HasExited property also exist in the 1.1 world, but aren't mentioned on the documentation page for Kill in 1.1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文