使用taskkill停止Windows服务

时间:2014-04-11 13:34:24

标签: c# windows service taskkill

我需要帮助才能使用C#终止Windows服务,现在使用以下选项终止服务:

来自cmd:

sc queryex ServiceName

发现服务的PID

taskkill /pid 1234(exemple) /f

4 个答案:

答案 0 :(得分:1)

为了便于阅读,我会将服务交互分离到它自己的类中,使用单独的方法IsServiceInstalled,IsServiceRunning,StopService ..等等,如果你理解我的意思。

同样通过停止服务它应该已经杀死了这个过程,但我也包含了你如何做这样的事情。如果服务不会停止并且您通过终止该过程来停止它,那么如果您无法正确构建服务代码,我会查看服务代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals("MyServiceNameHere"));
            if (sc != null)
            {
                if (sc.Status.Equals(ServiceControllerStatus.Running))
                {
                    sc.Stop();

                    Process[] procs = Process.GetProcessesByName("MyProcessName");
                    if (procs.Length > 0)
                    {
                        foreach (Process proc in procs)
                        {
                            //do other stuff if you need to find out if this is the correct proc instance if you have more than one
                            proc.Kill();
                        }
                    }
                }
            }
        }
    }
}

答案 1 :(得分:0)

如果您知道进程ID使用 Process.GetProcessById(Id)的.Kill(); 如果您知道进程名称使用 Process.GetProcessesByName(名称).Kill();

答案 2 :(得分:0)

此处代码使用4种方法来停止您的服务,包括TaskKill,请注意您必须具有足够的权限才能执行此操作。

  foreach (ServiceController Svc in ServiceController.GetServices())
    {
        using (Svc)
        {
            //The short name of "Microsoft Exchange Service Host"
            if (Svc.ServiceName.Equals("YourServiceName"))
            {
                if (Svc.Status != ServiceControllerStatus.Stopped)
                {
                    if (Svc.CanStop)
                    {
                        try
                        {
                            Svc.Stop();
                            Svc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 15));
                        }
                        catch
                        {
                            //Try to stop using Process
                            foreach (Process Prc in Process.GetProcessesByName(Svc.ServiceName))
                            {
                                using (Prc)
                                {
                                    try
                                    {
                                        //Try to kill the service process
                                        Prc.Kill();
                                    }
                                    catch
                                    {
                                        //Try to terminate the service using taskkill command
                                        Process.Start(new ProcessStartInfo
                                        {
                                            FileName = "cmd.exe",
                                            CreateNoWindow = true,
                                            UseShellExecute = false,
                                            Arguments = string.Format("/c taskkill /pid {0} /f", Prc.Id)
                                        });

                                        //Additional:
                                        Process.Start(new ProcessStartInfo
                                        {
                                            FileName = "net.exe",
                                            CreateNoWindow = true,
                                            UseShellExecute = false,
                                            Arguments = string.Format("stop {0}", Prc.ProcessName)
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

答案 3 :(得分:0)

Process.GetProcessesByName(“服务名称”)在我的情况下不起作用。 您将需要对System.ServiceProcess和System.Management的引用。

    public static void Kill()
    {
        int processId = GetProcessIdByServiceName(ServiceName);

        var process = Process.GetProcessById(processId);
        process.Kill();
    }

    private static int GetProcessIdByServiceName(string serviceName)
    {

        string qry = $"SELECT PROCESSID FROM WIN32_SERVICE WHERE NAME = '{serviceName }'";
        var searcher = new ManagementObjectSearcher(qry);
        var managementObjects = new ManagementObjectSearcher(qry).Get();

        if (managementObjects.Count != 1)
            throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', expected to find one process for service but found {managementObjects.Count}.");

        int processId = 0;

        foreach (ManagementObject mngntObj in managementObjects)
            processId = (int)(uint) mngntObj["PROCESSID"];

        if (processId == 0)
            throw new InvalidOperationException($"In attempt to kill a service '{serviceName}', process ID for service is 0. Possible reason is the service is already stopped.");

        return processId;
    }