From 667e75559dda586917e8f2ea87215378d38d00db Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 6 Oct 2022 20:07:22 -0700 Subject: [PATCH] On Unix, only explicitly terminate the native process if not in background (#18215) --- .../engine/NativeCommandProcessor.cs | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 6b8908c03c..65903305ef 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -422,7 +422,7 @@ namespace System.Management.Automation catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -444,7 +444,7 @@ namespace System.Management.Automation catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -904,7 +904,7 @@ namespace System.Management.Automation finally { // Do some cleanup - CleanUp(); + CleanUp(killBackgroundProcess: false); } // An exception was thrown while attempting to run the program @@ -1161,7 +1161,8 @@ namespace System.Management.Automation /// /// Aggressively clean everything up... /// - private void CleanUp() + /// If set, also terminate background process. + private void CleanUp(bool killBackgroundProcess) { // We need to call 'NotifyEndApplication' as appropriate during cleanup if (_hasNotifiedBeginApplication) @@ -1171,17 +1172,20 @@ namespace System.Management.Automation 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. #if UNIX - try + if (killBackgroundProcess || !_isRunningInBackground) { - _nativeProcess?.Kill(); - } - catch - { - // Ignore all exception since it is cleanup. + try + { + _nativeProcess?.Kill(); + } + catch + { + // Ignore all exceptions since it is cleanup. + } } #endif _nativeProcess?.Dispose();