Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out Windows service's running process name .NET 1.1

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?

like image 245
the berserker Avatar asked Feb 19 '09 14:02

the berserker


3 Answers

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.
                }
            }
        }
    }
}
like image 175
Daniel Richardson Avatar answered Sep 28 '22 07:09

Daniel Richardson


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.

like image 26
Richard Avatar answered Sep 28 '22 08:09

Richard


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.

like image 20
configurator Avatar answered Sep 28 '22 08:09

configurator