代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
//using System.Management;
//using System.Management.Instrumentation;
namespace CappW
{
class Program
{
///
/// Kill a process, and all of its children.
///
/// Process ID.
/* private static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
*/
public static void KillProc(string procname,int myid)
{
Process[] allProcess = Process.GetProcesses();
foreach (Process p in allProcess)
{
System.Console.WriteLine(p.ToString()+"->"+p.Id);
}
Process[] killprocess = Process.GetProcessesByName(procname);
foreach (Process p in killprocess)
{
if (myid != p.Id)
{
// KillProcessAndChildren(p.Id);
p.Kill();
}
}
//CappW.vshost
Process[] killprocess2 = Process.GetProcessesByName(procname + ".vshost");
foreach (Process p in killprocess2)
{
p.Kill();
}
}
static void Main(string[] args)
{
string knme = "CappW";
Random ran = new Random();
int aa = ran.Next(50, 80);
Process p2=Process.GetCurrentProcess();
int myid = p2.Id;
System.Console.WriteLine("starttime:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"));
KillProc(knme,myid);
for (int i = 0; i < 10; i++)
{
Thread.Sleep(aa * 200);
}
System.Console.WriteLine("endtime:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"));
}
}
}