Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping windows service with taskkill

I need help to kill a windows service using C#, now to kill the service use the following option:

From the cmd:

sc queryex ServiceName

After discovering the PID of the service

taskkill /pid 1234(exemple) /f
like image 785
Johnny Avatar asked Mar 20 '23 22:03

Johnny


2 Answers

For ease of reading but I would separate the services interactions into it's own class with separate methods IsServiceInstalled, IsServiceRunning, StopService ..etc if you get what I mean.

Also by stopping the service it should kill the process already but I included how you would do something like that as well. If the service won't stop and you are stopping it by killing the process, I would look at the service code if you have access to it wasn't built correctly.

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();
                        }
                    }
                }
            }
        }
    }
}
like image 93
Tsukasa Avatar answered Mar 27 '23 20:03

Tsukasa


Process.GetProcessesByName("service name") does not work in my case bu the below does. You will need references to System.ServiceProcess and to 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;
    }
like image 21
SashaArz Avatar answered Mar 27 '23 18:03

SashaArz