From 8189f9f8aa797763d06e50c48ec4250760c2d70a Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:14:00 -0500 Subject: [PATCH 1/2] Give programs an empty stdin by default, with -InheritStdin to opt out Programs the kit starts inherited PowerShell's own stdin, so one that reads its input could take input meant for the script, or wait for it until its time limit. They now get NUL (on the Process.Start path, a closed pipe). -InheritStdin, or a command's InheritStdin key, gives PowerShell's own back. Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 116 ++++++++++++++++++++++++++++++++- ParallelKit.ps1 | 140 ++++++++++++++++++++++++++++++---------- README.md | 11 ++-- 3 files changed, 229 insertions(+), 38 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d76cde5..07e04ca 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3810,7 +3810,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) @@ -5333,6 +5333,120 @@ Test-Assert ($bhRun.ExitCode -eq 1 -and $bhRun.Stdout -like '*No such section: Z Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BI' "programs get NUL as stdin, unless -InheritStdin") { +# In a fresh PowerShell with a file as its stdin, on each start path. cmd's +# set /p on a file takes one line and leaves the rest, so each program here +# that inherits stdin reads the next line, and one that doesn't reads nothing. +# Each is time-limited: a program left reading would otherwise hang the test. +Reset-Harness +$biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1") +$biInput = [System.IO.Path]::ChangeExtension($biScript, '.txt') +$biBat = [System.IO.Path]::ChangeExtension($biScript, '.cmd') +[System.IO.File]::WriteAllText($biInput, ((1..9 | ForEach-Object { 'line' + $_ }) -join "`r`n") + "`r`n") +[System.IO.File]::WriteAllText($biScript, @' +param([string]$Kit, [int]$Fallback) +$ErrorActionPreference = 'Stop' +. $Kit +[PkChildProcessJob]::TestUseProcessStart = ($Fallback -eq 1) +$read = @{ FilePath = 'cmd.exe'; Arguments = '/d /v:on /c "set L=none& set /p L=& echo [!L!]"' } +$out = @{} +function Invoke-One([string]$Name, [hashtable]$Extra) { + try { $script:out[$Name] = ([string](Invoke-PkProcessWithTimeout @read -TimeoutMs 8000 @Extra).Stdout).Trim() } catch { $script:out[$Name] = 'ERROR ' + $_ } +} +function Invoke-Batch([string]$Name, [hashtable]$Extra, [hashtable]$Key) { + $r = (Invoke-PkProcessBatch -Commands @($read + $Key) -TimeoutSeconds 8 @Extra).Results[0] + $script:out[$Name] = if ($r.TimedOut) { 'TIMED OUT' } elseif ($r.StartError) { 'ERROR ' + $r.StartError } else { ([string]$r.Stdout).Trim() } +} +function Invoke-Dispatch([string]$Name, [hashtable]$Extra, [hashtable]$Key) { + $feed = @{ Given = $false }; $got = @{ Text = 'no result' }; $job = $read + $Key + $null = Invoke-PkProcessDispatch -MaxConcurrent 1 -TimeoutSeconds 8 @Extra ` + -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @($job) }.GetNewClosure() ` + -JobFinalize { param($j, $q) $got.Text = if ($j['TimedOut']) { 'TIMED OUT' } else { ([string](Complete-PkProcess $j).Stdout).Trim() } }.GetNewClosure() + $script:out[$Name] = $got.Text +} +function Invoke-Start([string]$Name, [hashtable]$Extra) { + $j = Start-PkProcess @read @Extra + if (-not (Wait-PkProcess $j.Proc -TimeoutMs 8000)) { $null = Stop-PkProcessTree $j.Proc; $script:out[$Name] = 'TIMED OUT'; return } + $script:out[$Name] = ([string](Complete-PkProcess $j -Dispose).Stdout).Trim() +} +Invoke-Start 'start' @{} +Invoke-One 'one' @{} +Invoke-Batch 'batch' @{} @{} +Invoke-Dispatch 'dispatch' @{} @{} +# timeout.exe needs a console to read from, and says so at once without one. +$sw = [System.Diagnostics.Stopwatch]::StartNew() +$t = Invoke-PkProcessWithTimeout -FilePath ([Environment]::SystemDirectory + '/timeout.exe') -Arguments '/t 6' -TimeoutMs 15000 +$out['timeout'] = [string]$t.ExitCode + ' ' + ($sw.Elapsed.TotalSeconds -lt 4) + ' ' + (-not [string]::IsNullOrWhiteSpace($t.Stderr)) +if ((Get-Command Start-PkProcess).Parameters.ContainsKey('InheritStdin')) { + Invoke-Start 'start -InheritStdin' @{ InheritStdin = $true } + Invoke-One 'one -InheritStdin' @{ InheritStdin = $true } + Invoke-Batch 'batch -InheritStdin' @{ InheritStdin = $true } @{} + Invoke-Batch 'batch key' @{} @{ InheritStdin = $true } + Invoke-Batch 'batch -InheritStdin, key off' @{ InheritStdin = $true } @{ InheritStdin = $false } + Invoke-Batch 'batch key as text' @{} @{ InheritStdin = 'True' } + Invoke-Batch 'batch bad key' @{} @{ InheritStdin = 'maybe' } + Invoke-Dispatch 'dispatch -InheritStdin' @{ InheritStdin = $true } @{} + Invoke-Dispatch 'dispatch key' @{} @{ InheritStdin = $true } + Invoke-Dispatch 'dispatch -InheritStdin, key off' @{ InheritStdin = $true } @{ InheritStdin = $false } +} +foreach ($k in $out.Keys) { '{0}={1}' -f $k, $out[$k] } +'@) +# A .cmd, since the redirect needs cmd.exe. With -InheritStdin: its own stdin +# is the file, and the PowerShell it starts inherits that. +[System.IO.File]::WriteAllText($biBat, "@`"$selfExe`" -NoProfile -ExecutionPolicy Bypass -File `"$biScript`" -Kit `"$kitPath`" -Fallback %1 < `"$biInput`"`r`n") +try { + foreach ($biFallback in 0, 1) { + $biPath = @('CreatedInJob', 'Process.Start')[$biFallback] + $biRun = Invoke-PkProcessWithTimeout -FilePath $biBat -Arguments ([string]$biFallback) -TimeoutMs 120000 + $bi = @{} + foreach ($biLine in ([string]$biRun.Stdout -split "`r?`n")) { $biAt = $biLine.IndexOf('='); if ($biAt -gt 0) { $bi[$biLine.Substring(0, $biAt)] = $biLine.Substring($biAt + 1) } } + foreach ($biName in 'start', 'one', 'batch', 'dispatch') { + Test-Assert ($bi[$biName] -eq '[none]') ("a program reading stdin gets nothing and exits (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")") + } + Test-Assert ($bi['timeout'] -eq '1 True True') ("timeout.exe, which needs a console to read from, fails at once (" + $biPath + ": exit, quick, says why: " + $bi['timeout'] + ")") + $biNext = 1 + foreach ($biName in 'start -InheritStdin', 'one -InheritStdin', 'batch -InheritStdin', 'batch key', 'batch key as text', 'dispatch -InheritStdin', 'dispatch key') { + Test-Assert ($bi[$biName] -eq ('[line' + $biNext + ']')) ("it reads the script's stdin with the opt-in (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")") + $biNext++ + } + foreach ($biName in 'batch -InheritStdin, key off', 'dispatch -InheritStdin, key off') { + Test-Assert ($bi[$biName] -eq '[none]') ("a key of `$false overrides -InheritStdin (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")") + } + Test-Assert ([string]$bi['batch bad key'] -like 'ERROR *InheritStdin must be*maybe*') ("a bad InheritStdin key is that command's StartError (" + $biPath + ": " + $bi['batch bad key'] + ")") + } +} finally { + foreach ($biFile in $biScript, $biInput, $biBat) { [System.IO.File]::Delete($biFile) } +} + +# A console whose input code page is UTF-8: on .NET Framework, Process.Start +# writes a byte-order mark into a redirected stdin, which a program would read +# as input (kept as it is: only the fallback path, on 5.1, is affected, and +# the kit can't stop it). Read back through findstr, which prints any line it +# gets. +Reset-Harness +$biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1") +[System.IO.File]::WriteAllText($biScript, @' +param([string]$Kit) +. $Kit +$null = & chcp.com 65001 +[Console]::InputEncoding = [System.Text.Encoding]::UTF8 +foreach ($fallback in $false, $true) { + [PkChildProcessJob]::TestUseProcessStart = $fallback + $r = Invoke-PkProcessWithTimeout -FilePath findstr.exe -Arguments '/n "^"' -TimeoutMs 8000 + 'READ=' + ([string]$r.Stdout).Trim().Length + ' EXIT=' + $r.ExitCode +} +'@) +try { $biRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $biScript + '" -Kit "' + $kitPath + '"') -TimeoutMs 60000 } finally { [System.IO.File]::Delete($biScript) } +$biReads = @([regex]::Matches([string]$biRun.Stdout, 'READ=\d+ EXIT=\d+') | ForEach-Object { $_.Value }) -join '; ' +$biWanted = @('READ=0 EXIT=1; READ=0 EXIT=1') +if ($PSVersionTable.PSVersion.Major -lt 6) { $biWanted += 'READ=0 EXIT=1; READ=5 EXIT=0' } # "1:" and the mark's three bytes +Test-Assert ($biWanted -contains $biReads) ("stdin is empty with a UTF-8 console too, on both start paths, apart from 5.1's byte-order mark on the fallback (" + $biReads + ")") +Reset-Harness +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 7294386..815d7aa 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -163,7 +163,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 12; + public const int TypesVersion = 13; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -619,7 +619,8 @@ public static class PkChildProcessJob // // Everything else copies Process.Start with UseShellExecute = false: // command line, Windows' own search for a bare name, CREATE_NO_WINDOW, - // stdin, redirected stdout/stderr, and the default encoding. + // redirected stdout/stderr, and the default encoding. stdin is NUL, or + // PowerShell's own as Process.Start passes it. // // The pipe ends the child writes to must be inheritable while it's // created, and a plain Process.Start elsewhere in PowerShell inherits @@ -636,6 +637,9 @@ public static class PkChildProcessJob private const int STARTF_USESTDHANDLES = 0x100; private const int STD_INPUT_HANDLE = -10; private const uint HANDLE_FLAG_INHERIT = 1; + private const uint GENERIC_READ = 0x80000000; + private const uint FILE_SHARE_READ_WRITE = 3; + private const uint OPEN_EXISTING = 3; private static readonly IntPtr PROC_THREAD_ATTRIBUTE_HANDLE_LIST = (IntPtr)0x20002; private static readonly IntPtr PROC_THREAD_ATTRIBUTE_JOB_LIST = (IntPtr)0x2000D; @@ -689,6 +693,10 @@ public static class PkChildProcessJob [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, + ref SECURITY_ATTRIBUTES lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); + [DllImport("kernel32.dll", SetLastError = true)] private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize); @@ -867,13 +875,23 @@ public static class PkChildProcessJob } } + private static IntPtr OpenNulForRead() + { + SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); + sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); + sa.bInheritHandle = 1; + IntPtr nul = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ_WRITE, ref sa, OPEN_EXISTING, 0, IntPtr.Zero); + if (nul == new IntPtr(-1)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } + return nul; + } + // Starts the program in the job, or returns null when it can't do that // safely: the caller then uses Process.Start and Assign. fallbackReason // says why, for the caller's one-time warning; it stays null where no // warning is due (no job, which has its own; the harness switch). Throws // Win32Exception when Windows refuses to create the program, as // Process.Start does. encoding null: the console's output code page. - public static PkStartedProcess TryStart(string fileName, string arguments, string workingDirectory, Encoding encoding, out string fallbackReason) + public static PkStartedProcess TryStart(string fileName, string arguments, string workingDirectory, Encoding encoding, bool inheritStdin, out string fallbackReason) { fallbackReason = null; if (TestUseProcessStart || _job == IntPtr.Zero) { return null; } @@ -891,7 +909,7 @@ public static class PkChildProcessJob IntPtr attrSize = IntPtr.Zero; int handleCount = 0, jobCount = 0; bool attrReady = false, created = false, setupFailed = false; - IntPtr stdin = IntPtr.Zero; + IntPtr stdin = IntPtr.Zero, nul = IntPtr.Zero; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); startLock.Enter(); @@ -907,12 +925,23 @@ public static class PkChildProcessJob CreateOutputPipe(out outRead, out outWrite); CreateOutputPipe(out errRead, out errWrite); - // stdin as Process.Start passes it: PowerShell's own. Listed - // only if inheritable, the only case the child could use it. - stdin = GetStdHandle(STD_INPUT_HANDLE); - uint hflags; - bool stdinInherit = stdin != IntPtr.Zero && stdin != new IntPtr(-1) - && GetHandleInformation(stdin, out hflags) && (hflags & HANDLE_FLAG_INHERIT) != 0; + // NUL, so a program that reads its input gets the end of it + // at once. Or, asked for, PowerShell's own as Process.Start + // passes it: listed only if inheritable, the only case the + // child could use it. + bool stdinInherit = true; + if (inheritStdin) + { + stdin = GetStdHandle(STD_INPUT_HANDLE); + uint hflags; + stdinInherit = stdin != IntPtr.Zero && stdin != new IntPtr(-1) + && GetHandleInformation(stdin, out hflags) && (hflags & HANDLE_FLAG_INHERIT) != 0; + } + else + { + nul = OpenNulForRead(); + stdin = nul; + } handleCount = stdinInherit ? 3 : 2; handleArr = Marshal.AllocHGlobal(IntPtr.Size * handleCount); Marshal.WriteIntPtr(handleArr, 0, outWrite); @@ -981,6 +1010,7 @@ public static class PkChildProcessJob // output never reaches the end. if (outWrite != IntPtr.Zero) { CloseHandle(outWrite); } if (errWrite != IntPtr.Zero) { CloseHandle(errWrite); } + if (nul != IntPtr.Zero) { CloseHandle(nul); } if (!created) { if (outRead != IntPtr.Zero) { CloseHandle(outRead); } @@ -1039,7 +1069,7 @@ public static class PkChildProcessJob # A session that loaded an older copy keeps its compiled types. Say so, # rather than fail later with a missing-method error. Keep this number in # sync with [PkState]::TypesVersion. -if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 12) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 13) { throw "ParallelKit: this PowerShell session already loaded an older version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } @@ -1652,6 +1682,9 @@ function Start-PkProcess { # cap): past it, the first half and the last half, and the result's # StdoutDroppedChars and StderrDroppedChars say how many were left out. # The rest is still read, so the program never stalls on a full pipe. + # .PARAMETER InheritStdin + # Give the program PowerShell's own stdin. Without it, the program's input + # is empty: one that reads it gets the end of it at once. # .OUTPUTS # A hashtable @{ Proc; StdoutTask; StderrTask; Stopwatch }. Proc is the # program's Process. Read its output from StdoutTask and StderrTask: Proc's @@ -1662,12 +1695,13 @@ function Start-PkProcess { $Arguments = "", [string]$WorkingDirectory = "", $OutputEncoding = $null, - [int]$MaxOutputChars = 0 + [int]$MaxOutputChars = 0, + [switch]$InheritStdin ) # Invoke-PkProcessWithTimeout, Invoke-PkProcessBatch and Invoke-PkProcessDispatch # make the same check, naming themselves: keep the four in step. if ($MaxOutputChars -lt 0) { throw ("Start-PkProcess: -MaxOutputChars must be 0 (no cap) or more (got " + $MaxOutputChars + "). It's how many characters of each output stream to keep.") } - return (Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -CallerState $PSCmdlet.SessionState) + return (Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState) } function Start-PkProcessCore { @@ -1681,6 +1715,7 @@ function Start-PkProcessCore { [string]$WorkingDirectory = "", $OutputEncoding = $null, [int]$MaxOutputChars = 0, + [switch]$InheritStdin, [System.Management.Automation.SessionState]$CallerState ) $encoding = Resolve-PkEncoding -Encoding $OutputEncoding @@ -1699,6 +1734,10 @@ function Start-PkProcessCore { } $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true + # On the Process.Start path, an empty stdin is a pipe closed at once below. + # On .NET Framework with a UTF-8 console, Process.Start itself has written a + # byte-order mark into it by then, and takes no encoding to stop that. + $psi.RedirectStandardInput = -not $InheritStdin $psi.CreateNoWindow = $true # Relative paths mean your current location, not the process's working @@ -1728,13 +1767,16 @@ function Start-PkProcessCore { # Process.Start, and the job just after (a child it starts at once # can miss it then). $fallbackReason = $null - $started = [PkChildProcessJob]::TryStart($psi.FileName, $psi.Arguments, $psi.WorkingDirectory, $encoding, [ref]$fallbackReason) + $started = [PkChildProcessJob]::TryStart($psi.FileName, $psi.Arguments, $psi.WorkingDirectory, $encoding, $InheritStdin, [ref]$fallbackReason) if ($null -eq $started) { # Once per process: the cost is the same for every program after. if ($null -ne $fallbackReason -and [PkChildProcessJob]::ClaimFallbackWarning()) { Write-PkMessage ("[WARNING] Starting programs with Process.Start and adding them to the Job Object just after, because " + $fallbackReason + ". A child a program starts straight away (cmd /c tool.exe) can escape the cleanup if PowerShell is killed outright. Shown once.") -Level Warn } $proc = [System.Diagnostics.Process]::Start($psi) + if (-not $InheritStdin) { + try { $proc.StandardInput.Close() } catch { } # nothing is written, so a failed close is a pipe whose program has already gone + } } } catch { $tried = "" @@ -1935,6 +1977,19 @@ function Get-PkJobMaxOutputChars { return [int]$cap } +function Get-PkJobSwitch { + # A job's own $true/$false key (InheritStdin), else the default: the + # engine's switch of the same name. Throws on anything else, as + # Get-PkJobTimeLimit does for TimeoutSeconds. Text is taken ('True', as a + # CSV gives it), but not a number. + param([hashtable]$Job, [string]$Key, [bool]$Default = $false) + $value = $Job[$Key] + if ($null -eq $value) { return $Default } + $on = $false + if (-not [bool]::TryParse([string]$value, [ref]$on)) { throw ($Key + " must be `$true or `$false (got '" + $value + "').") } + return $on +} + function Stop-PkTimedOutJob { # Kills a dispatcher job's program tree once it passes its TimeLimit and # sets TimedOut; the job is then finalized like any other. Only a .Proc @@ -2175,6 +2230,9 @@ function Invoke-PkProcessWithTimeout { # .PARAMETER MaxOutputChars # Keep at most this many characters of each output stream, as for # Start-PkProcess (default 0, no cap). + # .PARAMETER InheritStdin + # Give the program PowerShell's own stdin, as for Start-PkProcess. Without + # it, the program's input is empty. # .PARAMETER IgnoreAbort # Keep going during an abort, for a cleanup or restore step that has to run # because of it. @@ -2193,6 +2251,7 @@ function Invoke-PkProcessWithTimeout { [string]$WorkingDirectory = "", $OutputEncoding = $null, [int]$MaxOutputChars = 0, + [switch]$InheritStdin, [switch]$IgnoreAbort ) # Checked before starting anything: 0 or less would kill the program at once. @@ -2202,7 +2261,7 @@ function Invoke-PkProcessWithTimeout { # Start-PkProcess, Invoke-PkProcessBatch and Invoke-PkProcessDispatch make the # same check: keep the four in step. if ($MaxOutputChars -lt 0) { throw ("Invoke-PkProcessWithTimeout: -MaxOutputChars must be 0 (no cap) or more (got " + $MaxOutputChars + "). It's how many characters of each output stream to keep.") } - $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -CallerState $PSCmdlet.SessionState + $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState try { # Short slices, so an abort or cancel is noticed within a moment. $waited = [System.Diagnostics.Stopwatch]::StartNew() @@ -2253,9 +2312,10 @@ function Invoke-PkProcessDispatch { # OutputWaitOver, OutputWaitMs. It also sets Group to # the job's group, unless the job already has a Group of its own. The default # starter reads FilePath, Arguments (a string as written, or a list quoted one - # argument per element), WorkingDirectory, OutputEncoding and MaxOutputChars - # from the job. A job's TimeoutSeconds key overrides -TimeoutSeconds, and its - # MaxOutputChars key -MaxOutputChars. + # argument per element), WorkingDirectory, OutputEncoding, MaxOutputChars and + # InheritStdin from the job. A job's TimeoutSeconds key overrides + # -TimeoutSeconds, its MaxOutputChars key -MaxOutputChars, and its InheritStdin + # key -InheritStdin. # .PARAMETER GroupProvider # { } returning the next group, or $null when there are no more, and # outputting nothing else. Return a list as one group with a comma: @@ -2314,6 +2374,10 @@ function Invoke-PkProcessDispatch { # For the default starter: keep at most this many characters of each job's # output streams, as for Start-PkProcess (default 0, no cap). A job's own # MaxOutputChars key overrides it, and 0 there opts the job out. + # .PARAMETER InheritStdin + # For the default starter: give each job's program PowerShell's own stdin, + # as for Start-PkProcess. Without it, its input is empty. A job's own + # InheritStdin key overrides it either way. # .OUTPUTS # An object with GroupResults, Aborted, ForceKilledCount and # JobStarterFailedCount. Each group result has GroupInfo (the group), Completed @@ -2343,7 +2407,8 @@ function Invoke-PkProcessDispatch { # Complete-PkProcess's and Invoke-PkProcessBatch's -StreamTimeoutMs # default to the same 15000: keep the three in step. [int]$StreamTimeoutMs = 15000, - [int]$MaxOutputChars = 0 + [int]$MaxOutputChars = 0, + [switch]$InheritStdin ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -2364,7 +2429,8 @@ function Invoke-PkProcessDispatch { $pkTimeoutSeconds = $TimeoutSeconds $pkStreamTimeoutMs = $StreamTimeoutMs $pkMaxOutputChars = $MaxOutputChars - Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds, StreamTimeoutMs, MaxOutputChars -Scope Local + $pkInheritStdin = $InheritStdin.IsPresent + Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds, StreamTimeoutMs, MaxOutputChars, InheritStdin -Scope Local # 0 or less would never start a job (or pull a group) and spin forever. if ($pkMaxConcurrent -isnot [System.Threading.SemaphoreSlim]) { @@ -2398,7 +2464,7 @@ function Invoke-PkProcessDispatch { $pkCallerState = $PSCmdlet.SessionState $pkJobStarter = { param($pkJob) - $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobMaxOutputChars -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) + $pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobMaxOutputChars -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin) # Start-PkProcessCore's four keys (it builds them in two places); the # batch's starter copies them too: a new key goes in all four. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask @@ -3001,13 +3067,13 @@ function Invoke-PkProcessBatch { # .DESCRIPTION # Each command is a hashtable: @{ FilePath = ...; Arguments = ... } plus, # optionally, WorkingDirectory, OutputEncoding (overrides -OutputEncoding), - # TimeoutSeconds (overrides -TimeoutSeconds) and any keys of your own, which - # come back on the result's Command. Inside - # Invoke-PkRun, Ctrl+C lets running programs finish (up to -AbortTimeoutSeconds) - # and starts no new ones; a second Ctrl+C kills them right away. Every - # command is tried, and one that can't start gets a StartError on its result. - # Repeats of the same failure for the same program are reported once, with a - # count at the end. + # TimeoutSeconds (overrides -TimeoutSeconds), MaxOutputChars, InheritStdin + # (which override the parameters of the same names) and any keys of your + # own, which come back on the result's Command. Inside Invoke-PkRun, Ctrl+C + # lets running programs finish (up to -AbortTimeoutSeconds) and starts no new + # ones; a second Ctrl+C kills them right away. Every command is tried, and one + # that can't start gets a StartError on its result. Repeats of the same failure + # for the same program are reported once, with a count at the end. # .PARAMETER Commands # The command hashtables. $null or empty returns no results. # .PARAMETER MaxConcurrent @@ -3032,6 +3098,10 @@ function Invoke-PkProcessBatch { # Keep at most this many characters of each program's output streams, as # for Start-PkProcess (default 0, no cap). A command's own MaxOutputChars # key overrides it, and 0 there opts the command out. + # .PARAMETER InheritStdin + # Give each program PowerShell's own stdin, as for Start-PkProcess. Without + # it, its input is empty. A command's own InheritStdin key overrides it + # either way. # .OUTPUTS # An object with Results, Aborted and ForceKilledCount. Each result has Command, # ExitCode, Stdout, Stderr, StreamTimedOut, StreamError, StartError, Aborted, @@ -3056,7 +3126,8 @@ function Invoke-PkProcessBatch { # Complete-PkProcess's and Invoke-PkProcessDispatch's -StreamTimeoutMs # default to the same 15000: keep the three in step. [int]$StreamTimeoutMs = 15000, - [int]$MaxOutputChars = 0 + [int]$MaxOutputChars = 0, + [switch]$InheritStdin ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -3069,7 +3140,8 @@ function Invoke-PkProcessBatch { $pkOutputEncoding = $OutputEncoding $pkStreamTimeoutMs = $StreamTimeoutMs $pkMaxOutputChars = $MaxOutputChars - Remove-Variable -Name Commands, MaxConcurrent, OnComplete, AbortTimeoutSeconds, TimeoutSeconds, OutputEncoding, StreamTimeoutMs, MaxOutputChars -Scope Local + $pkInheritStdin = $InheritStdin.IsPresent + Remove-Variable -Name Commands, MaxConcurrent, OnComplete, AbortTimeoutSeconds, TimeoutSeconds, OutputEncoding, StreamTimeoutMs, MaxOutputChars, InheritStdin -Scope Local # Checked once here, so a bad name fails the call instead of every command. $null = Resolve-PkEncoding -Encoding $pkOutputEncoding @@ -3098,6 +3170,7 @@ function Invoke-PkProcessBatch { $pkStartProcessCore = ${function:Start-PkProcessCore} $pkGetJobTimeLimit = ${function:Get-PkJobTimeLimit} $pkGetJobMaxOutputChars = ${function:Get-PkJobMaxOutputChars} + $pkGetJobSwitch = ${function:Get-PkJobSwitch} $pkGetStartFailureCause = ${function:Get-PkStartFailureCause} $pkWriteCallbackLoopWarning = ${function:Write-PkCallbackLoopWarning} # Invoke-PkCallback's -PkContext: callbacks that used continue/break are @@ -3140,11 +3213,12 @@ function Invoke-PkProcessBatch { try { $null = & $pkGetJobTimeLimit -Job $pkC $pkCap = & $pkGetJobMaxOutputChars -Job $pkC -DefaultMaxOutputChars $pkMaxOutputChars + $pkStdin = & $pkGetJobSwitch -Job $pkC -Key 'InheritStdin' -Default $pkInheritStdin } catch { & $pkReportStartFailure $pkC $_ continue } - $pkJobs.Add(@{ FilePath = $pkC['FilePath']; Arguments = $pkC['Arguments']; WorkingDirectory = [string]$pkC['WorkingDirectory']; OutputEncoding = $pkEncoding; TimeoutSeconds = $pkC['TimeoutSeconds']; MaxOutputChars = $pkCap; Command = $pkC }) + $pkJobs.Add(@{ FilePath = $pkC['FilePath']; Arguments = $pkC['Arguments']; WorkingDirectory = [string]$pkC['WorkingDirectory']; OutputEncoding = $pkEncoding; TimeoutSeconds = $pkC['TimeoutSeconds']; MaxOutputChars = $pkCap; InheritStdin = $pkStdin; Command = $pkC }) } return $pkJobs }.GetNewClosure() @@ -3152,7 +3226,7 @@ function Invoke-PkProcessBatch { $pkJobStarter = { param($pkJob) try { - $pkStarted = & $pkStartProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory $pkJob['WorkingDirectory'] -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars $pkJob['MaxOutputChars'] + $pkStarted = & $pkStartProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory $pkJob['WorkingDirectory'] -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars $pkJob['MaxOutputChars'] -InheritStdin:$pkJob['InheritStdin'] } catch { $pkJob['StartFailureReported'] = $true & $pkReportStartFailure $pkJob['Command'] $_ @@ -3213,7 +3287,7 @@ function Get-PkWorkerSafeFunctionNames { return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', 'Get-PkProcessDuration', 'Resolve-PkEncoding', 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJobs', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobMaxOutputChars', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobMaxOutputChars', 'Get-PkJobSwitch', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { diff --git a/README.md b/README.md index 82b42bd..a4f82c2 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ Programs run in your current location (`Get-Location`) unless a command says oth
-Defaults, time limits and output caps +Defaults, time limits, output caps and input `-OnComplete` runs as each command finishes, but only for commands that actually ran. Check `Results` for the ones that couldn't start or were aborted. A progress counter driven from `-OnComplete` won't reach the total if any did, so count from `$batch.Results` afterwards for the final numbers. Defaults: `-MaxConcurrent` 4, `-AbortTimeoutSeconds` 60 (how long Ctrl+C waits for running programs), `-TimeoutSeconds` 0 (no limit). The runspace engine's names, `-MaxParallel` and `-DrainTimeoutSeconds`, work here too, and on the dispatcher. @@ -249,7 +249,9 @@ Programs run in your current location (`Get-Location`) unless a command says oth `-MaxOutputChars 100000` keeps at most 100,000 characters of each program's stdout and stderr. Past that, the first half and the last half are kept, so the start and the end of a long log are both there, and `StdoutDroppedChars` / `StderrDroppedChars` say how many characters were left out. The rest is still read, so the program never stalls on a full pipe. The default, 0, keeps everything. A command's own `MaxOutputChars` key overrides it; 0 opts that command out. `Start-PkProcess`, `Invoke-PkProcessWithTimeout` and the dispatcher take it too. -Both per-command keys go on the command itself, for example one that keeps all of its output and gets 30 seconds: `@{ FilePath = 'tool.exe'; Arguments = @('x'); MaxOutputChars = 0; TimeoutSeconds = 30 }`. +A program's input (stdin) is empty: one that reads it gets the end of it at once, rather than waiting for input or taking what was meant for your script. `-InheritStdin` gives programs PowerShell's own stdin instead, as they had before 3.5. A command's own `InheritStdin` key, `$true` or `$false`, overrides it either way. `Start-PkProcess`, `Invoke-PkProcessWithTimeout` and the dispatcher take it too. `timeout.exe` (`cmd /c timeout /t 5`) refuses to run with empty input: "Input redirection is not supported". To wait inside a command, use `ping -n 6 127.0.0.1 >nul` (about 5 seconds). `-InheritStdin` brings `timeout.exe` back only if your script's own stdin is a console. + +The per-command keys go on the command itself, for example one that keeps all of its output and gets 30 seconds: `@{ FilePath = 'tool.exe'; Arguments = @('x'); MaxOutputChars = 0; TimeoutSeconds = 30 }`. `-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). @@ -521,7 +523,7 @@ All of these callbacks run on whichever thread called the dispatcher: the main t - **With your own `-JobPollCompleted`**, none of this applies: `Complete-PkProcess` waits as it does anywhere else. - To retry a job or add follow-up work, enqueue job hashtables onto `$pending` inside `-JobFinalize`. They join the same group, and the group isn't complete until they've all finished. A retry can start within milliseconds of the failure, so cap the number of retries, and don't count on the gap for something like a locked file to clear. - `-JobAbortCleanup { param($job) }` is called for each job an abort killed or kept from starting, to remove its partial output. -- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` works the same way, with a job's `MaxOutputChars` key, for the default starter. The killed job still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. +- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` and `-InheritStdin` work the same way, with a job's `MaxOutputChars` and `InheritStdin` keys, for the default starter. The killed job still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. - The dispatcher keeps its state on the job hashtables. Don't use these names for your own job fields: `GroupKey`, `SlotReleased`, `Proc`, `StdoutTask`, `StderrTask`, `Stopwatch`, `TimeLimit`, `TimedOut`, `StartFailureReported`, `OutputWait`, `OutputWaitOver`, `OutputWaitMs`. (`Group` is yours if you set it yourself.)
@@ -615,7 +617,8 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort - After changing `ParallelKit.ps1` itself, start a new PowerShell window. A session keeps the kit's compiled parts until it closes; the kit tells you if it finds an older copy loaded. - One `Invoke-PkRun` at a time per PowerShell process: a call made while one is already running, nested or from another runspace, just runs inside it. Several dispatchers can run at once inside one run (one per runspace job, say); they share its abort state and can share a `SemaphoreSlim` to enforce a combined concurrency limit. - A worker stuck inside a long .NET call can't be interrupted. Force-stop stops waiting for it and returns. The worker is NOT killed: once that call returns it can carry on to the end of its script. Before any step that can't be undone (deleting a source file, say), have the worker check `Test-PkCancelRequested` and skip the step if it's true. -- Programs run hidden, and there's no way to send them input. A program that stops to ask a question will sit there until it's killed. +- Programs run hidden, and there's no way to send them input. A program that reads its stdin finds it empty, so one that stops to ask a question usually gives up or takes its default. One that reads the keyboard directly (through a console of its own) sits there until it's killed, as does one that waits on your script's stdin under `-InheritStdin`. `timeout.exe` won't run at all without `-InheritStdin` and a console; see [Run a list of programs](#run-a-list-of-programs). +- If a program can't be started inside the Job Object (`Initialize-ParallelKit`'s `StartMode` isn't `CreatedInJob`, or the one-time warning says so), then on Windows PowerShell with a UTF-8 console its stdin isn't quite empty: .NET Framework puts a byte-order mark in it. - A program's output is collected in memory and handed over when it exits; there's no live line-by-line output. A program that prints gigabytes will use that much memory, unless `-MaxOutputChars` caps what's kept. A batch keeps every result, output included, until it returns, which adds up over thousands of chatty programs. If you only need the output in `-OnComplete`, drop it there with `$result.Stdout = $null; $result.Stderr = $null` and it's freed as the batch goes. - Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations). From 492b38a1c52b60c604e619b257cd918791586145 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:14:28 -0500 Subject: [PATCH 2/2] Harness: clearer comments in section BI Co-Authored-By: Claude Opus 5.5 --- ParallelKit.Harness.ps1 | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 07e04ca..3bff812 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5393,8 +5393,7 @@ if ((Get-Command Start-PkProcess).Parameters.ContainsKey('InheritStdin')) { } foreach ($k in $out.Keys) { '{0}={1}' -f $k, $out[$k] } '@) -# A .cmd, since the redirect needs cmd.exe. With -InheritStdin: its own stdin -# is the file, and the PowerShell it starts inherits that. +# A .cmd, since it takes cmd.exe to start PowerShell with a file as its stdin. [System.IO.File]::WriteAllText($biBat, "@`"$selfExe`" -NoProfile -ExecutionPolicy Bypass -File `"$biScript`" -Kit `"$kitPath`" -Fallback %1 < `"$biInput`"`r`n") try { foreach ($biFallback in 0, 1) { @@ -5422,9 +5421,8 @@ try { # A console whose input code page is UTF-8: on .NET Framework, Process.Start # writes a byte-order mark into a redirected stdin, which a program would read -# as input (kept as it is: only the fallback path, on 5.1, is affected, and -# the kit can't stop it). Read back through findstr, which prints any line it -# gets. +# as input. Only the fallback path on 5.1, where Process.Start takes no +# encoding for it. Read back through findstr, which prints any line it gets. Reset-Harness $biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1") [System.IO.File]::WriteAllText($biScript, @'