LoginSignup
12
12

More than 5 years have passed since last update.

子プロセス以下のプロセスツリーを強制終了

Last updated at Posted at 2014-10-17

子プロセスを強制終了する場合、最もシンプルな実装ではProcess.Kill()メソッドを利用すればよい。

void KillChildProcess(System.Diagnostics.Process process)
{
  process.Kill();
}

ただし、子プロセスがさらに別プロセス(自プロセスから見た子孫プロセス)を起動している場合、Process.Kill()メソッドでは子プロセスだけを強制終了し孫プロセス以下は生き残ってしまう。

Windows(XP以降?)ではOS標準でtaskkillコマンドが提供されるため、同コマンドにより子プロセス以下のプロセスツリー全体を強制終了できる。

void KillProcessTree(System.Diagnostics.Process process)
{
  string taskkill = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "taskkill.exe");
  using (var procKiller = new System.Diagnostics.Process()) {
    procKiller.StartInfo.FileName = taskkill;
    procKiller.StartInfo.Arguments = string.Format("/PID {0} /T /F", process.Id);
    procKiller.StartInfo.CreateNoWindow = true;
    procKiller.StartInfo.UseShellExecute = false;
    procKiller.Start();
    procKiller.WaitForExit();
  }
}

C#のみで頑張る実装も考えられるが面倒くさそう。
http://msdn.microsoft.com/ja-jp/vstudio/aa569609#Question3 http://blogs.msdn.com/b/bclteam/archive/2006/06/20/640259.aspx 地獄っぽい

12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12