diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 86def59..f0ce80d 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1477,6 +1477,34 @@ $cleanup = $null try { $cleanup = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 3 127.0.0.1' -IgnoreAbort } catch { } Test-Assert ($null -ne $cleanup -and $cleanup.ExitCode -eq 0) "-IgnoreAbort lets a cleanup program run to the end during an abort" +# A program quick enough to finish before the abort was looked at used to run. +# Each writes a file, so a run leaves a trace. +$quickDir = Join-Path $env:TEMP ("pk-harness-quick-" + $PID) +$null = New-Item -ItemType Directory -Force -Path $quickDir +$quickError = $null +try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\abort.txt"') } catch { $quickError = [string]$_ } +Test-Assert ($quickError -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\abort.txt'))) ("during an abort, a quick program isn't started (" + $quickError + ")") +$quick = $null +try { $quick = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments ('/c echo ran> "' + $quickDir + '\ignore.txt"') -IgnoreAbort } catch { } +Test-Assert ($null -ne $quick -and (Test-Path -LiteralPath ($quickDir + '\ignore.txt'))) "-IgnoreAbort still runs it" +Reset-Harness +# The same in a worker, when its run is canceled rather than aborted. +$quickCts = [System.Threading.CancellationTokenSource]::new() +$quickCrash = [System.Collections.Generic.List[string]]::new() +$quickPolls = @{ Count = 0 } +$null = Invoke-PkRunspaceJobs -MaxParallel 1 -Cts $quickCts -DrainTimeoutSeconds 20 -JobParams (New-JobList -Jobs @(@{ Cmd = $cmdExe; Dir = $quickDir })) ` + -PollCallback { $quickPolls.Count++; if ($quickPolls.Count -eq 3) { $quickCts.Cancel() } }.GetNewClosure() ` + -JobCrashedHandler { param($e) $quickCrash.Add([string]$e.Exception.InnerException.Message) }.GetNewClosure() -WorkerScript { + param($Cmd, $Dir) + $waited = [System.Diagnostics.Stopwatch]::StartNew() + while (-not (Test-PkCancelRequested) -and $waited.Elapsed.TotalSeconds -lt 15) { [System.Threading.Thread]::Sleep(20) } + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\ignored.txt"') -IgnoreAbort + $null = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments ('/c echo ran> "' + $Dir + '\cancel.txt"') + } +Test-Assert ($quickCrash.Count -eq 1 -and $quickCrash[0] -like "*wasn't started because the run is being aborted*" -and -not (Test-Path -LiteralPath ($quickDir + '\cancel.txt')) -and (Test-Path -LiteralPath ($quickDir + '\ignored.txt'))) ("in a worker whose run is canceled, a quick program isn't started, except with -IgnoreAbort (" + ($quickCrash -join '; ') + ")") +$quickCts.Dispose() +Remove-Item -LiteralPath $quickDir -Recurse -Force -ErrorAction SilentlyContinue + # A job's own Group field is left alone. Reset-Harness $feed = @{ Given = $false } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index d618f85..b1af98b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2244,7 +2244,8 @@ function Invoke-PkProcessWithTimeout { # .DESCRIPTION # Throws if the program had to be killed: because it ran past -TimeoutMs, or # because the run was aborted or canceled while it was going. Anything the - # program started is killed with it. + # program started is killed with it. During an abort or cancel it throws + # without starting the program. # .PARAMETER FilePath # The program to run. # .PARAMETER Arguments @@ -2270,8 +2271,8 @@ function Invoke-PkProcessWithTimeout { # nothing it left behind holds its output open. Only for a program Windows # gave a Job Object of its own, the normal case. # .PARAMETER IgnoreAbort - # Keep going during an abort, for a cleanup or restore step that has to run - # because of it. + # Start and keep going during an abort, for a cleanup or restore step that has + # to run because of it. # .OUTPUTS # Complete-PkProcess's object: ExitCode, Stdout, Stderr, StreamTimedOut, # StreamError, Duration (how long the program ran, from its start to its @@ -2298,6 +2299,9 @@ 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.") } + # Here as well as in the loop, which only looks after its first wait: a + # quick program would have run to the end by then. + if (-not $IgnoreAbort -and ((Test-PkAbortSignal) -or (Test-PkCancelRequested))) { throw ("'" + $FilePath + "' wasn't started because the run is being aborted") } $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState $job['KillTree'] = $KillTreeOnExit.IsPresent try { diff --git a/README.md b/README.md index 23d0df5..70dd329 100644 --- a/README.md +++ b/README.md @@ -561,7 +561,7 @@ For one program at a time, outside the engines. All of these are safe in worker | Function | Use | |---|---| -| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | +| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns the [process result](#process-results) fields marked "all". If it overruns, or the run is aborted, the program is killed and this **throws**; called while an abort or cancel is already in force, it throws without starting the program. Add `-IgnoreAbort` for a cleanup step that must run anyway. | | `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is a `.bat` or `.cmd`. | | `Start-PkProcess -FilePath -Arguments` | Start one hidden, with output captured in the background. Returns `@{ Proc; StdoutTask; StderrTask; Stopwatch }`; throws if it can't start. | | `Wait-PkProcess -Process -TimeoutMs` | Wait for exit with a timeout that can't overrun. Returns `$true` if it exited. |