简体   繁体   中英

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

我有一个控制台应用程序使用WMI ManagementClass生成其他win32进程。当用户通过proc Explorer或按ctrl + c杀死控制台应用程序时,我有一个要求,该应用程序应终止其创建的所有子进程。实现这一目标的方法?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM