Search code examples
windowsservicedetectionstatus

Detect windows service failure


Is it possible for one windows service to detect whether one of the other running windows services have stopped?

For some reason, 3rd party services are sometimes stopping, and I have to manually start them again. I need a service to automate this annoying process.


Solution

  • I would strongly advise you target your efforts on correcting the issues diagnosed instead of fire-fighting the symptoms. Find out why the third party services are stopping / failing and nip the issues in the bud.

    However, if you must implement something in the time being, take a look at ServiceController, with information found at this MSDN link. This will allow you to query services, their states, and further control them, as in calling Start, as required, for your particular case.

    Assuming (maybe against better judgement) that your'e using .NET, and, due to my affinity to it, C# as the language, consider the following for a quick off-the-cuff example:

    //Add a reference to System.ServiceProcess
    
    using System.ServiceProcess;
    
    var services = ServiceController.GetServices();
    foreach (var service in services)
    {
        if (service.ServiceName == myServiceName &&
            service.Status == ServiceControllerStatus.Stopped)
        {
            service.Start();
        }
    }