开发者

How to terminate child processes when a c# console application is aborted?

I have a console application that spawns other wi开发者_StackOverflow社区n32 processes using WMI ManagementClass.I have a requirement when a user kills the console application through proc explorer or by pressing ctrl+c ,the application should terminate all the child processes it created.What is the best way to achive this?


Keeping in mind that you have to take in your needs into account, you can do it like the sample below.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace KillSpawnedProcesses
{
    class Program
    {
        static List<int> _processes = new List<int>();

        static void Main(string[] args)
        {
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);

            StartProcesses();
            Console.Read(); //to hold up console
            Console.Read(); //to hold up console
        }

        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            KillProcesses();
        }

        static void StartProcesses()
        {
            for(int i = 0; i < 2; i++)
            {
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo();
                p.StartInfo.FileName = "Notepad.exe";
                p.Start();
                _processes.Add(p.Id);
            }
        }

        static void KillProcesses()
        {
            foreach(var p in _processes)
            {
                Process tempProcess = Process.GetProcessById(p);
                tempProcess.Kill();
            }            
        }
    }
}


If the sub-process has a message queue (Win32 message pumping), you can post WM_CLOSE to its main window, or define your own message. Otherwise, you can design your inter-process notification by using Sockets, Pipes, or Synchronization objects like Events.

The worst way is to kill the sub-processes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜