如何终止使用C#在WXP(和新的MS Windows中)所有[宏大]子进程 [英] How to terminate all [grand]child processes using C# on WXP (and newer MSWindows)

查看:168
本文介绍了如何终止使用C#在WXP(和新的MS Windows中)所有[宏大]子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:我怎样才能确定孩子的的进程树的杀了他们

Question: How can I determine all processes in the child's Process Tree to kill them?

我所有的进程?有一个应用程序,在C#编写将:

I have an application, written in C# that will:


  1. 从服务器,

  2. 获得的一组数据
  3. 生成一个第三方工具来处理数据,然后

  4. 结果返回给服务器。

这是工作的罚款。但是,由于运行所消耗的 CPU的大量的和的可以的需要长达一个小时,我想补充有我的应用程序终止其子进程的能力。

This is working fine. But since a run consumes a lot of CPU and may take as long as an hour, I want to add the ability to have my app terminate its child processes.

的一些问题,使简单的解决方案,我发现其他地方有:

Some issues that make the simple solutions I've found elsewhere are:


  • 我的应用程序的子进程A(InstallAnywhere的EXE我认为)会产生真正的处理程序B(A 的java.exe 的),这反过来滋生更多的孩子C1..道道通(的这些都是用Java编写的)。

  • 有可能会的多我的应用程序的副本的(因此,多套的子女)在同一台机器上运行。

  • 的子进程是不是在我的控制,因此有可能在未来的某个D的进程。

  • 我的应用程序必须在32位的的64位MS Windows中的版本。

  • My app's child process "A" (InstallAnywhere EXE I think) spawns the real processing app "B" (a java.exe), which in turns spawns more children "C1".."Cn" (most of which are also written in Java).
  • There will likely be multiple copies of my application (and hence, multiple sets of its children) running on the same machine.
  • The child process is not in my control so there might be some "D" processes in the future.
  • My application must run on 32-bit and 64-bit versions of MSWindows.

在加运行侧面没有数据丢失的问题,一个干净关机无所谓,只要过程很快结束。

On the plus side there is no issue of data loss, a "clean" shutdown doesn't matter as long as the processes end fairly quickly.

推荐答案

我想你可以从的 MSDN论坛的。

public bool killProcess(int pid)
 {
  bool didIkillAnybody = false;
  try
  {
   Process[] procs = Process.GetProcesses();
   for (int i = 0; i < procs.Length; i++)
   {
    didIkillAnybody = GetParentProcess(procsIdea.Id) == pid) &&
                                   killProcess(procsIdea.Id);
   }
   try
   {
    Process myProc = Process.GetProcessById(pid);
    myProc.Kill();
    return true;
   }
   catch { }
  }
  catch (Exception ex)
  {
   try
   {
    new Logger().Write("Exception caught at JobExecution.killProcess()", ex.Message, System.Diagnostics.EventLogEntryType.Warning, false);
   }
   catch { }
  }
  return didIkillAnybody;
 }

 private int GetParentProcess(int Id)
 {
  int parentPid = 0;
  using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))
  {
   mo.Get();
   parentPid = Convert.ToInt32(mo["ParentProcessId"]);
  }
  return parentPid;
 }

这篇关于如何终止使用C#在WXP(和新的MS Windows中)所有[宏大]子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆