Skip to content

Commit 668d72c

Browse files
authored
Clean up the IPC named pipe on PowerShell exit (PowerShell#12187)
1 parent 238cb5c commit 668d72c

3 files changed

Lines changed: 110 additions & 29 deletions

File tree

‎src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -707,7 +707,7 @@ internal static IReadOnlyCollection<PSHostProcessInfo> GetAppDomainNamesFromProc
707707
else if (process.ProcessName.Equals(pName, StringComparison.Ordinal))
708708
{
709709
// only add if the process name matches
710-
procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName));
710+
procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe));
711711
}
712712
}
713713
}
@@ -736,6 +736,12 @@ internal static IReadOnlyCollection<PSHostProcessInfo> GetAppDomainNamesFromProc
736736
/// </summary>
737737
public sealed class PSHostProcessInfo
738738
{
739+
#region Members
740+
741+
private readonly string _pipeNameFilePath;
742+
743+
#endregion
744+
739745
#region Properties
740746

741747
/// <summary>
@@ -781,29 +787,60 @@ public string MainWindowTitle
781787
private PSHostProcessInfo() { }
782788

783789
/// <summary>
784-
/// Constructor.
790+
/// Initializes a new instance of the PSHostProcessInfo type.
785791
/// </summary>
786792
/// <param name="processName">Name of process.</param>
787793
/// <param name="processId">Id of process.</param>
788794
/// <param name="appDomainName">Name of process AppDomain.</param>
789-
internal PSHostProcessInfo(string processName, int processId, string appDomainName)
795+
/// <param name="pipeNameFilePath">File path of pipe name.</param>
796+
internal PSHostProcessInfo(
797+
string processName,
798+
int processId,
799+
string appDomainName,
800+
string pipeNameFilePath)
790801
{
791-
if (string.IsNullOrEmpty(processName)) { throw new PSArgumentNullException("processName"); }
802+
if (string.IsNullOrEmpty(processName))
803+
{
804+
throw new PSArgumentNullException(nameof(processName));
805+
}
792806

793-
if (string.IsNullOrEmpty(appDomainName)) { throw new PSArgumentNullException("appDomainName"); }
807+
if (string.IsNullOrEmpty(appDomainName))
808+
{
809+
throw new PSArgumentNullException(nameof(appDomainName));
810+
}
794811

795812
MainWindowTitle = string.Empty;
796813
try
797814
{
798815
var proc = Process.GetProcessById(processId);
799816
MainWindowTitle = proc.MainWindowTitle ?? string.Empty;
800817
}
801-
catch (ArgumentException) { }
802-
catch (InvalidOperationException) { }
818+
catch (ArgumentException)
819+
{
820+
// Window title is optional.
821+
}
822+
catch (InvalidOperationException)
823+
{
824+
// Window title is optional.
825+
}
803826

804827
this.ProcessName = processName;
805828
this.ProcessId = processId;
806829
this.AppDomainName = appDomainName;
830+
_pipeNameFilePath = pipeNameFilePath;
831+
}
832+
833+
#endregion
834+
835+
#region Methods
836+
837+
/// <summary>
838+
/// Retrieves the pipe name file path.
839+
/// </summary>
840+
/// <returns>Pipe name file path.</returns>
841+
public string GetPipeNameFilePath()
842+
{
843+
return _pipeNameFilePath;
807844
}
808845

809846
#endregion

‎src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -560,9 +560,7 @@ static RemoteSessionNamedPipeServer()
560560

561561
CreateIPCNamedPipeServerSingleton();
562562

563-
#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
564-
CreateAppDomainUnloadHandler();
565-
#endif
563+
CreateProcessExitHandler();
566564
}
567565

568566
#endregion
@@ -961,30 +959,31 @@ internal static void CreateIPCNamedPipeServerSingleton()
961959
}
962960
}
963961

964-
#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
965-
private static void CreateAppDomainUnloadHandler()
962+
private static void CreateProcessExitHandler()
966963
{
967-
// Subscribe to the app domain unload event.
968-
AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
964+
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
965+
{
966+
IPCNamedPipeServerEnabled = false;
967+
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
968+
if (namedPipeServer != null)
969969
{
970-
IPCNamedPipeServerEnabled = false;
971-
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
972-
if (namedPipeServer != null)
970+
try
973971
{
974-
try
975-
{
976-
// Terminate the IPC thread.
977-
namedPipeServer.Dispose();
978-
}
979-
catch (ObjectDisposedException) { }
980-
catch (Exception)
981-
{
982-
// Don't throw an exception on the app domain unload event thread.
983-
}
972+
// Terminate the IPC thread.
973+
namedPipeServer.Dispose();
984974
}
985-
};
975+
catch (ObjectDisposedException)
976+
{
977+
// Ignore if object already disposed.
978+
}
979+
catch (Exception)
980+
{
981+
// Don't throw an exception on the app domain unload event thread.
982+
}
983+
}
984+
};
986985
}
987-
#endif
986+
988987
private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
989988
{
990989
if (args.RestartListener)

‎test/powershell/Modules/Microsoft.PowerShell.Core/Get-PSHostProcessInfo.Tests.ps1‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,49 @@ Describe "Get-PSHostProcessInfo tests" -Tag CI {
5353
$psProcess.Count | Should -BeGreaterOrEqual 1
5454
$psProcess.ProcessId | Should -Contain $powershell.id
5555
}
56+
57+
It "Verifies named pipe filepath get method" {
58+
$pipeFilePath = (Get-PSHostProcessInfo -Id $pid).GetPipeNameFilePath()
59+
$pipeFilePath | Should -Exist
60+
}
61+
62+
It "Verifies named pipe filepath is removed on process exit" {
63+
$aliveFile = Join-Path -Path $TestDrive -ChildPath 'AliveFileXXZZ.txt'
64+
"" | Out-File -FilePath $aliveFile
65+
$testfilePath = Join-Path -Path $TestDrive -ChildPath 'TestScriptXXZZ.ps1'
66+
@'
67+
param (
68+
[string] $LiveFilePath
69+
)
70+
71+
$count = 0
72+
while ((Test-Path -Path $LiveFilePath) -and ($count++ -lt 60))
73+
{
74+
Start-Sleep -Milliseconds 500
75+
}
76+
77+
exit
78+
'@ | Out-File -FilePath $testfilePath
79+
80+
# Create PowerShell process to monitor.
81+
$psFileName = $IsWindows ? 'pwsh.exe' : 'pwsh'
82+
$psPath = Join-Path -Path $PSHOME -ChildPath $psFileName
83+
$psProc = Start-Process -FilePath $psPath -ArgumentList "-File $testfilePath -LiveFilePath $aliveFile" -PassThru
84+
Wait-UntilTrue -sb {
85+
(Get-PSHostProcessInfo -Id $psProc.Id) -ne $null
86+
} -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250
87+
88+
# Verify named pipe file path.
89+
$psNamedPipePath = (Get-PSHostProcessInfo -Id $psProc.Id).GetPipeNameFilePath()
90+
$psNamedPipePath | Should -Exist
91+
92+
# Signal PowerShell test process to exit normally.
93+
Remove-Item -Path $aliveFile -Force -ErrorAction Ignore
94+
Wait-UntilTrue -sb {
95+
(Test-Path -Path $psNamedPipePath) -eq $false
96+
} -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250
97+
98+
# Verify named pipe file path is removed.
99+
$psNamedPipePath | Should -Not -Exist
100+
}
56101
}

0 commit comments

Comments
 (0)