Skip to content

Commit 6540a95

Browse files
[release/v7.2.7] On Unix, only explicitly terminate the native process if not in background (#18280)
Co-authored-by: Steve Lee <slee@microsoft.com>
1 parent b8602c8 commit 6540a95

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

src/System.Management.Automation/engine/NativeCommandProcessor.cs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues)
326326
catch (Exception)
327327
{
328328
// Do cleanup in case of exception
329-
CleanUp();
329+
CleanUp(killBackgroundProcess: true);
330330
throw;
331331
}
332332
}
@@ -348,7 +348,7 @@ internal override void ProcessRecord()
348348
catch (Exception)
349349
{
350350
// Do cleanup in case of exception
351-
CleanUp();
351+
CleanUp(killBackgroundProcess: true);
352352
throw;
353353
}
354354
}
@@ -782,7 +782,7 @@ internal override void Complete()
782782
finally
783783
{
784784
// Do some cleanup
785-
CleanUp();
785+
CleanUp(killBackgroundProcess: false);
786786
}
787787

788788
// An exception was thrown while attempting to run the program
@@ -1060,7 +1060,8 @@ internal void StopProcessing()
10601060
/// <summary>
10611061
/// Aggressively clean everything up...
10621062
/// </summary>
1063-
private void CleanUp()
1063+
/// <param name="killBackgroundProcess">If set, also terminate background process.</param>
1064+
private void CleanUp(bool killBackgroundProcess)
10641065
{
10651066
// We need to call 'NotifyEndApplication' as appropriate during cleanup
10661067
if (_hasNotifiedBeginApplication)
@@ -1070,23 +1071,23 @@ private void CleanUp()
10701071

10711072
try
10721073
{
1073-
if (_nativeProcess != null)
1074-
{
1075-
// on Unix, we need to kill the process to ensure it terminates as Dispose() merely
1076-
// closes the redirected streams and the processs does not exit on macOS. However,
1077-
// on Windows, a winexe like notepad should continue running so we don't want to kill it.
1074+
// on Unix, we need to kill the process (if not running in background) to ensure it terminates,
1075+
// as Dispose() merely closes the redirected streams and the process does not exit.
1076+
// However, on Windows, a winexe like notepad should continue running so we don't want to kill it.
10781077
#if UNIX
1078+
if (killBackgroundProcess || !_isRunningInBackground)
1079+
{
10791080
try
10801081
{
1081-
_nativeProcess.Kill();
1082+
_nativeProcess?.Kill();
10821083
}
10831084
catch
10841085
{
1085-
// Ignore all exception since it is cleanup.
1086+
// Ignore all exceptions since it is cleanup.
10861087
}
1087-
#endif
1088-
_nativeProcess.Dispose();
10891088
}
1089+
#endif
1090+
_nativeProcess.Dispose();
10901091
}
10911092
catch (Exception)
10921093
{

0 commit comments

Comments
 (0)