I have a console application that spawns other win32 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?
views:
136answers:
2
+3
A:
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();
}
}
}
}
FernandoZ
2010-01-28 06:30:02
A:
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.
Dudu
2010-01-28 06:40:51