Skip to content
30 changes: 17 additions & 13 deletions src/System.Management.Automation/engine/NativeCommandProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues)
catch (Exception)
{
// Do cleanup in case of exception
CleanUp();
CleanUp(killBackgroundProcess: true);
throw;
}
}
Expand All @@ -444,7 +444,7 @@ internal override void ProcessRecord()
catch (Exception)
{
// Do cleanup in case of exception
CleanUp();
CleanUp(killBackgroundProcess: true);
throw;
}
}
Expand Down Expand Up @@ -904,7 +904,7 @@ internal override void Complete()
finally
{
// Do some cleanup
CleanUp();
CleanUp(killBackgroundProcess: false);
}

// An exception was thrown while attempting to run the program
Expand Down Expand Up @@ -1161,7 +1161,8 @@ internal void StopProcessing()
/// <summary>
/// Aggressively clean everything up...
/// </summary>
private void CleanUp()
/// <param name="killBackgroundProcess">If set, also terminate background process.</param>
private void CleanUp(bool killBackgroundProcess)
{
// We need to call 'NotifyEndApplication' as appropriate during cleanup
if (_hasNotifiedBeginApplication)
Expand All @@ -1171,17 +1172,20 @@ private void CleanUp()

try
{
// on Unix, we need to kill the process to ensure it terminates as Dispose() merely
// closes the redirected streams and the processs does not exit on macOS. However,
// on Windows, a winexe like notepad should continue running so we don't want to kill it.
// on Unix, we need to kill the process (if not running in background) to ensure it terminates,
// as Dispose() merely closes the redirected streams and the process does not exit.
// However, on Windows, a winexe like notepad should continue running so we don't want to kill it.
Comment thread
SteveL-MSFT marked this conversation as resolved.
Resolved
#if UNIX
try
{
_nativeProcess?.Kill();
}
catch
if (killBackgroundProcess || !_isRunningInBackground)
{
// Ignore all exception since it is cleanup.
try
Comment thread
SteveL-MSFT marked this conversation as resolved.
Resolved
{
_nativeProcess?.Kill();
}
catch
{
// Ignore all exceptions since it is cleanup.
}
}
#endif
_nativeProcess?.Dispose();
Expand Down