Kill child processes when parent windows service is killed via task manager

Viewed 228

Firstly, I know that child processes can be killed when parent process (not running as service) is killed via Task Manager.

However, if parent process is running as windows service, the parent and child processes are not displayed in a tree structure in Task Manager. As a result, when parent service is killed, child processes still run.

Is there a way to kill child processes when parent service is killed via Task Manager?

I can't modify the code of child process. So I can't add code in it to periodically check the existence of parent's PID.


Minimal code to reproduce my issue:

// parent service
    class Program
    {
        static void Main(string[] args)
        {
            var host = Host
                .CreateDefaultBuilder(args)
                .UseWindowsService()
                .Build();

            var startInfo = new ProcessStartInfo
            {
                FileName = "Test.ChildProcessApp.exe"
            };

            Process.Start(startInfo);
            host.Run();
        }
    }

// child process
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(3000);
            }
        }
    }
1 Answers

In OnStop() of parent service you can stop the child process

ServiceController service = new ServiceController(ChildName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
  }
  catch
  {
    // ...
  }
Related