首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用taskkill停止windows服务

使用taskkill停止windows服务
EN

Stack Overflow用户
提问于 2014-04-11 21:34:24
回答 4查看 6.7K关注 0票数 4

我需要使用C#来终止windows服务的帮助,现在要终止该服务,请使用以下选项:

从cmd:

代码语言:javascript
复制
sc queryex ServiceName

在发现服务的PID之后

代码语言:javascript
复制
taskkill /pid 1234(exemple) /f
EN

回答 4

Stack Overflow用户

发布于 2014-04-11 22:00:55

为了便于阅读,但如果你明白我的意思,我会将服务交互分离到它自己的类中,分别使用IsServiceInstalled,IsServiceRunning,StopService ..etc方法。

同样,通过停止服务,它应该已经杀死了进程,但我也包括了如何做这样的事情。如果服务不停止,而您通过终止进程来停止它,如果您有权访问未正确构建的服务代码,我将查看服务代码。

代码语言:javascript
复制
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();
                        }
                    }
                }
            }
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2018-05-22 00:58:09

在我的例子中,Process.GetProcessesByName(“服务名称”)不起作用,但下面的例子起作用。您需要引用System.ServiceProcess和System.Management。

代码语言:javascript
复制
    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;
    }
票数 2
EN

Stack Overflow用户

发布于 2014-04-13 03:27:17

这里的代码使用了4种方法来停止你的服务,包括TaskKill,注意你必须有足够的特权才能这样做。

代码语言:javascript
复制
  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)
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23014152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档