Skip to content

Instantly share code, notes, and snippets.

@alx9r
Last active December 3, 2024 23:21
Show Gist options
  • Save alx9r/d82232d53356dc5d10eaab1d83458d0e to your computer and use it in GitHub Desktop.
Save alx9r/d82232d53356dc5d10eaab1d83458d0e to your computer and use it in GitHub Desktop.
Repro of lock up raising `CTRL_C_EVENT` from runspace connect via named pipe in `pwsh` job process
# https://stackoverflow.com/a/79248980/1404637
# https://gist.github.com/alx9r/d82232d53356dc5d10eaab1d83458d0e
$before = Get-Process pwsh | % Id
$job = Start-Job {
begin { 'begin' | Set-Content .\log.txt }
end {
Start-Sleep -Seconds 1000
'end' | Add-Content .\log.txt
}
clean { 'clean' | Add-Content .\log.txt }
}
Start-Sleep -Seconds 1
$jobProcessId =
Compare-Object `
-ReferenceObject $before `
-DifferenceObject (Get-Process pwsh | % id) |
% InputObject
$jobProcessId
Function Stop-PowerShellProcess {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[int]
$ProcessId
)
$connInfo = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($ProcessId)
$runspace = [RunspaceFactory]::CreateRunspace($connInfo)
try {
$runspace.Open()
$ps = [PowerShell]::Create($runspace)
$ps.AddScript(@'
Add-Type -Namespace Kernel32 -Name Native -MemberDefinition @"
[DllImport("kernel32.dll", EntryPoint = "GenerateConsoleCtrlEvent")]
private static extern bool GenerateConsoleCtrlEventNative(
int dwCtrlEvent,
int dwProcessGroupId);
public static void GenerateConsoleCtrlEvent(int eventId, int processGroupId)
{
if (!GenerateConsoleCtrlEventNative(eventId, processGroupId))
{
throw new System.ComponentModel.Win32Exception();
}
}
"@
[Kernel32.Native]::GenerateConsoleCtrlEvent(0, 0)
'@).Invoke()
foreach ($e in $ps.Streams.Error) {
Write-Error -ErrorRecord $e
}
}
finally {
$runspace.Dispose()
}
}
Start-Sleep -Seconds 1
Stop-PowerShellProcess -ProcessId $jobProcessId
Start-Sleep -Seconds 1
Get-Content .\log.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment