Skip to content

Commit 667e755

Browse files
authored
On Unix, only explicitly terminate the native process if not in background (PowerShell#18215)
1 parent 7073525 commit 667e755

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

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

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues)
422422
catch (Exception)
423423
{
424424
// Do cleanup in case of exception
425-
CleanUp();
425+
CleanUp(killBackgroundProcess: true);
426426
throw;
427427
}
428428
}
@@ -444,7 +444,7 @@ internal override void ProcessRecord()
444444
catch (Exception)
445445
{
446446
// Do cleanup in case of exception
447-
CleanUp();
447+
CleanUp(killBackgroundProcess: true);
448448
throw;
449449
}
450450
}
@@ -904,7 +904,7 @@ internal override void Complete()
904904
finally
905905
{
906906
// Do some cleanup
907-
CleanUp();
907+
CleanUp(killBackgroundProcess: false);
908908
}
909909

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

11721173
try
11731174
{
1174-
// on Unix, we need to kill the process to ensure it terminates as Dispose() merely
1175-
// closes the redirected streams and the processs does not exit on macOS. However,
1176-
// on Windows, a winexe like notepad should continue running so we don't want to kill it.
1175+
// on Unix, we need to kill the process (if not running in background) to ensure it terminates,
1176+
// as Dispose() merely closes the redirected streams and the process does not exit.
1177+
// However, on Windows, a winexe like notepad should continue running so we don't want to kill it.
11771178
#if UNIX
1178-
try
1179-
{
1180-
_nativeProcess?.Kill();
1181-
}
1182-
catch
1179+
if (killBackgroundProcess || !_isRunningInBackground)
11831180
{
1184-
// Ignore all exception since it is cleanup.
1181+
try
1182+
{
1183+
_nativeProcess?.Kill();
1184+
}
1185+
catch
1186+
{
1187+
// Ignore all exceptions since it is cleanup.
1188+
}
11851189
}
11861190
#endif
11871191
_nativeProcess?.Dispose();

0 commit comments

Comments
 (0)