Skip to content

Commit

Permalink
Recursively kill process + children. Fix #661 #662
Browse files Browse the repository at this point in the history
  • Loading branch information
JimBobSquarePants committed Jun 7, 2018
1 parent d37a890 commit bd99d05
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
Expand Down
32 changes: 28 additions & 4 deletions src/ImageProcessor.Web.Plugins.PostProcessor/PostProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ namespace ImageProcessor.Web.Plugins.PostProcessor
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management;
using System.Web;

using ImageProcessor.Configuration;
Expand Down Expand Up @@ -120,11 +121,11 @@ private static PostProcessingResultEventArgs RunProcess(Uri url, string sourceFi

ProcessStartInfo start = new ProcessStartInfo("cmd")
{
WindowStyle = ProcessWindowStyle.Hidden,
//WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = PostProcessorBootstrapper.Instance.WorkingPath,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true
// CreateNoWindow = true
};

Process process = null;
Expand All @@ -144,18 +145,41 @@ private static PostProcessingResultEventArgs RunProcess(Uri url, string sourceFi

process.Start();

// Recursively kill all child processes.
void KillProcessAndChildren(int pid)
{
using (var searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={pid}"))
{
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementBaseObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}

try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch
{
// Process already exited.
}
}
}

// Wait for processing to finish, but not more than our timeout.
if (!process.WaitForExit(timeout))
{
process.Kill();
KillProcessAndChildren(process.Id);
ImageProcessorBootstrapper.Instance.Logger.Log(
typeof(PostProcessor),
$"Unable to post process image for request {url} within {timeout}ms. Original image returned.");
}
}
catch (Exception ex)
{
// Some security policies don't allow execution of programs in this way
// Some security policies don't allow execution of programs in this way.
ImageProcessorBootstrapper.Instance.Logger.Log(typeof(PostProcessor), ex.Message);
}
finally
Expand Down

0 comments on commit bd99d05

Please sign in to comment.