From 1df4236e6c0950067d20126c3916084a27277f89 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 26 Apr 2021 15:10:35 -0700 Subject: [PATCH] Kill native processes in pipeline when pipeline is disposed on Unix (#15287) --- .../engine/NativeCommandProcessor.cs | 14 +++++++++++++- .../NativeCommandProcessor.Tests.ps1 | 6 ++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 6899a1de0e..32f2ee1f7e 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1018,9 +1018,21 @@ namespace System.Management.Automation try { - // Dispose the process if it's already created if (_nativeProcess != null) { + // 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. +#if UNIX + try + { + _nativeProcess.Kill(); + } + catch + { + // Ignore all exception since it is cleanup. + } +#endif _nativeProcess.Dispose(); } } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 95eb59857a..8bef53a952 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -43,6 +43,12 @@ Describe 'native commands with pipeline' -tags 'Feature' { $result[0] | Should -Match "pwsh" } } + + It 'native command should be killed when pipeline is disposed' -Skip:($IsWindows) { + $yes = (Get-Process 'yes' -ErrorAction Ignore).Count + yes | Select-Object -First 2 + (Get-Process 'yes' -ErrorAction Ignore).Count | Should -Be $yes + } } Describe "Native Command Processor" -tags "Feature" {