diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d60f9d1..0e0822c 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1449,7 +1449,9 @@ $parentJob.Proc.Dispose(); if ($null -ne $childProc) { $childProc.Dispose() } # A large kill: taskkill prints a line per process it kills (three per # `cmd /c ping` tree). Left unread, that fills its output pipe and taskkill # blocks until the 10 s wait gives up, leaving most children running. -$many = @(1..40 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments (& $nestedPing 49) }) +# Started without tree jobs, so the kill goes to taskkill. +[PkChildProcessJob]::TestNoTreeJob = $true +try { $many = @(1..40 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments (& $nestedPing 49) }) } finally { [PkChildProcessJob]::TestNoTreeJob = $false } $waitMany = [System.Diagnostics.Stopwatch]::StartNew() while ((Get-HarnessPingCount 49) -lt 40 -and $waitMany.Elapsed.TotalSeconds -lt 15) { Start-Sleep -Milliseconds 200 } $startedMany = Get-HarnessPingCount 49 @@ -3395,7 +3397,10 @@ function Protect-HarnessPingChild { } Reset-Harness -$tkStart = Start-PkProcess -FilePath $cmdExe -Arguments ('/c ""' + $pingExe + '" -n 7 127.0.0.1"') +# Without a tree job, so the kill goes to taskkill. Section BF has the same +# protected child killed through the tree job. +[PkChildProcessJob]::TestNoTreeJob = $true +try { $tkStart = Start-PkProcess -FilePath $cmdExe -Arguments ('/c ""' + $pingExe + '" -n 7 127.0.0.1"') } finally { [PkChildProcessJob]::TestNoTreeJob = $false } $tkChild = Protect-HarnessPingChild -Parent $tkStart.Proc $tkKilled = Stop-PkProcessTree -Process $tkStart.Proc $tkNote = if ($null -ne $tkChild -and -not $tkChild.HasExited) { "the protected child survived" } else { "taskkill killed the child anyway, so this run doesn't exercise the failure path" } @@ -4266,6 +4271,8 @@ Test-Assert $compiled "the stand-in taskkill compiles" if ($compiled) { $tkLog = [System.IO.Path]::ChangeExtension($tkExe, '.log') $env:PK_FAKE_TASKKILL_LOG = $tkLog + # These test the taskkill path: no tree jobs. + [PkChildProcessJob]::TestNoTreeJob = $true try { # Five programs, an argument limit that fits two PIDs: several # taskkill calls, each under the limit. The stand-in fails, so the @@ -4292,6 +4299,7 @@ if ($compiled) { foreach ($h in $tkHung) { Stop-Process -Id $h.ProcessId -Force -ErrorAction SilentlyContinue } foreach ($p in $tkProcs) { $p.Dispose() } } finally { + [PkChildProcessJob]::TestNoTreeJob = $false Remove-Item Env:PK_FAKE_TASKKILL_LOG, Env:PK_FAKE_TASKKILL_MODE -ErrorAction SilentlyContinue try { [System.IO.File]::Delete($tkLog) } catch { } # temp file only; best effort } @@ -4302,7 +4310,9 @@ if ($compiled) { } # The real taskkill, one PID per call: each call still kills the whole tree. -$tkStarted = @(1..3 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments '/d /c ping -n 30 127.0.0.1 >nul' }) +# Without tree jobs, so the kill goes to taskkill. +[PkChildProcessJob]::TestNoTreeJob = $true +try { $tkStarted = @(1..3 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments '/d /c ping -n 30 127.0.0.1 >nul' }) } finally { [PkChildProcessJob]::TestNoTreeJob = $false } $tkPings = @() foreach ($s in $tkStarted) { $p = $null @@ -4963,6 +4973,94 @@ foreach ($beWhich in 'Start-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-P Test-Assert (@($beErrors | Where-Object { $_ -ne 'ok' }).Count -eq 0 -and $beStarted.Count -eq 0) ("-MaxOutputChars -1 is refused by all four before anything starts (" + ($beErrors -join ' | ') + ")") Write-Host "" +Write-Host "=== BF: a kill reaches a child whose parent already exited ===" -ForegroundColor Cyan +# The program pings for a second, runs an inner cmd that starts a ping +# (-w 4325) and exits at once, leaving that ping orphaned, then pings +# (-w 4326) itself. taskkill /T finds a tree through parent PIDs, so it +# missed the orphan; each program's own Job Object doesn't. +Reset-Harness +function Get-HarnessTagPings([string]$Tag) { return @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w $Tag %'") } +function Stop-HarnessTagPings { foreach ($tag in '4325', '4326', '4327') { foreach ($p in (Get-HarnessTagPings $tag)) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } } } +function Wait-HarnessTagPings([string[]]$Tags) { + $sw = [System.Diagnostics.Stopwatch]::StartNew() + while ($sw.Elapsed.TotalSeconds -lt 10) { + if (@($Tags | Where-Object { @(Get-HarnessTagPings $_).Count -eq 0 }).Count -eq 0) { return $true } + Start-Sleep -Milliseconds 100 + } + return $false +} +$bfOrphanArgs = '/d /c ping -n 2 127.0.0.1 >nul & ' + $cmdExe + ' /d /c start /b ping -n 60 -w 4325 127.0.0.1 >nul & ping -n 60 -w 4326 127.0.0.1 >nul' +try { + foreach ($bfMode in 'created in the job', 'Process.Start fallback') { + [PkChildProcessJob]::TestUseProcessStart = ($bfMode -ne 'created in the job') + try { $bfJob = Start-PkProcess -FilePath $cmdExe -Arguments $bfOrphanArgs } finally { [PkChildProcessJob]::TestUseProcessStart = $false } + $bfUp = Wait-HarnessTagPings @('4325', '4326') + $bfHas = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + $bfKilled = Stop-PkProcessTree -Process $bfJob['Proc'] + $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + Start-Sleep -Milliseconds 300 + $bfOrphans = @(Get-HarnessTagPings '4325').Count; $bfOwn = @(Get-HarnessTagPings '4326').Count + Test-Assert ($bfUp -and $bfHas -and $bfKilled -and $bfReleased -and $bfJob['Proc'].HasExited -and $bfOrphans -eq 0 -and $bfOwn -eq 0) ($bfMode + ": Stop-PkProcessTree kills a child whose parent already exited, and lets go of the tree job (both pings up: " + $bfUp + ", tree job: " + $bfHas + ", released: " + $bfReleased + ", orphans left " + $bfOrphans + ", own left " + $bfOwn + ")") + $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 -Dispose + Stop-HarnessTagPings + } + + # The time limit: the program and its orphan go, and the orphan no + # longer holds the job's output for the stream timeout after the kill. + $sw = [System.Diagnostics.Stopwatch]::StartNew() + $bfB = Invoke-PkProcessBatch -TimeoutSeconds 3 -Commands @(@{ FilePath = $cmdExe; Arguments = $bfOrphanArgs }) + $sw.Stop() + Start-Sleep -Milliseconds 300 + $bfOrphans = @(Get-HarnessTagPings '4325').Count + Test-Assert ($bfB.Results[0].TimedOut -and $bfOrphans -eq 0 -and $sw.Elapsed.TotalSeconds -lt 8) ("batch: a time-limit kill takes the orphan too, and the job ends soon after (" + [math]::Round($sw.Elapsed.TotalSeconds, 1) + " s, orphans left " + $bfOrphans + ")") + Stop-HarnessTagPings + + # An abort's force-stop. + Reset-PkAbortState + $bfB = Invoke-PkProcessBatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 -OnComplete { param($c, $r) if ($c['Key'] -eq 'quick') { Request-PkAbort } } -Commands @(@{ FilePath = $cmdExe; Arguments = $bfOrphanArgs; Key = 'tree' }, @{ FilePath = $cmdExe; Arguments = '/d /c ping -n 4 127.0.0.1 >nul'; Key = 'quick' }) + Reset-PkAbortState + Start-Sleep -Milliseconds 300 + $bfOrphans = @(Get-HarnessTagPings '4325').Count + Test-Assert ($bfB.Aborted -and $bfB.ForceKilledCount -eq 1 -and $bfOrphans -eq 0) ("batch: an abort's force-stop takes the orphan too (force-stopped " + $bfB.ForceKilledCount + ", orphans left " + $bfOrphans + ")") + Stop-HarnessTagPings + + # If Windows refuses to nest the tree job, the program still starts, + # without one, and a kill goes to taskkill. + [PkChildProcessJob]::TestRefuseTreeJob = $true + try { $bfJob = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c echo refused& ping -n 30 -w 4327 127.0.0.1 >nul' } finally { [PkChildProcessJob]::TestRefuseTreeJob = $false } + $bfUp = Wait-HarnessTagPings @('4327') + $bfHas = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + $bfKilled = Stop-PkProcessTree -Process $bfJob['Proc'] + Start-Sleep -Milliseconds 300 + $bfR = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 2000 -Dispose + Test-Assert ($bfUp -and -not $bfHas -and $bfKilled -and @(Get-HarnessTagPings '4327').Count -eq 0 -and $bfR.Stdout -match 'refused') ("a start where Windows refuses the tree job runs without one, and taskkill still kills its tree (tree job: " + $bfHas + ", killed: " + $bfKilled + ", output '" + ([string]$bfR.Stdout).Trim() + "')") + Stop-HarnessTagPings + + # A child that refuses PROCESS_TERMINATE still goes: the job is ended as a whole. + $bfStart = Start-PkProcess -FilePath $cmdExe -Arguments ('/c ""' + $pingExe + '" -n 7 127.0.0.1"') + $bfChild = Protect-HarnessPingChild -Parent $bfStart.Proc + $bfKilled = Stop-PkProcessTree -Process $bfStart.Proc + $bfGone = ($null -ne $bfChild -and $bfChild.WaitForExit(3000)) + Test-Assert ($null -ne $bfChild -and $bfKilled -and $bfGone) ("a child that refuses to be terminated is killed with its program's tree job (child found: " + ($null -ne $bfChild) + ", gone: " + $bfGone + ")") + $null = Complete-PkProcess -Job $bfStart -StreamTimeoutMs 0 -Dispose + if ($null -ne $bfChild) { $bfChild.Dispose() } + + # Unchanged: a program that exits on its own leaves what it started + # running, and Complete-PkProcess lets go of its tree job. + $bfJob = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c start /b ping -n 30 -w 4327 127.0.0.1 >nul' + $null = Wait-PkProcess -Process $bfJob['Proc'] -TimeoutMs 10000 + $bfUp = Wait-HarnessTagPings @('4327') + $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 + $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + $bfJob['Proc'].Dispose() + Test-Assert ($bfUp -and @(Get-HarnessTagPings '4327').Count -eq 1 -and $bfReleased) ("a leftover from a program that exits on its own keeps running, and the tree job is released (leftover up: " + $bfUp + ", released: " + $bfReleased + ")") +} finally { + [PkChildProcessJob]::TestUseProcessStart = $false + Stop-HarnessTagPings + Reset-PkAbortState +} +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 2d386dc..6d5f40f 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -160,11 +160,10 @@ public static class PkState public static bool AbortLatched = false; public static bool CloseAbort = false; public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default - public static volatile bool ThreadPoolRaised = false; // 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 = 10; + public const int TypesVersion = 11; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -236,6 +235,7 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; +using System.Runtime.CompilerServices; using Microsoft.Win32.SafeHandles; public sealed class PkStartedProcess @@ -415,6 +415,10 @@ public sealed class PkStreamReadTask : Task // A Windows Job Object with KILL_ON_JOB_CLOSE: every child process assigned // to it dies when this process exits for ANY reason, force-kill included. +// Each program the kit starts also gets a job of its own (its tree job), +// nested in that one, so the program and everything it started can be +// killed at once (KillTree), including a child whose parent has already +// exited, which taskkill /T can't find. public static class PkChildProcessJob { private const int JobObjectExtendedLimitInformation = 9; @@ -464,6 +468,66 @@ public static class PkChildProcessJob [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool TerminateJobObject(IntPtr hJob, uint uExitCode); + + // A program's tree job, closed by ReleaseTree or, failing that, when its + // Process object is collected. Without KILL_ON_JOB_CLOSE: closing it + // leaves whatever is still running in the kit's job, as before. + private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid + { + public TreeJob(IntPtr h) : base(true) { SetHandle(h); } + protected override bool ReleaseHandle() { return CloseHandle(handle); } + } + private static readonly ConditionalWeakTable _treeJobs = new ConditionalWeakTable(); + + // Harness only: start programs without a tree job, to test the taskkill + // path; or have TryStart's first CreateProcess, with the tree job, count + // as refused, to test its retry without one. + public static bool TestNoTreeJob = false; + public static bool TestRefuseTreeJob = false; + + private static void AddTree(Process process, IntPtr treeJob) + { + try { _treeJobs.Add(process, new TreeJob(treeJob)); } + catch (ArgumentException) { CloseHandle(treeJob); } // already has one (can't happen: each start is a new Process) + } + + // Kills every process in the program's tree job. False if it has none, + // or Windows refused: the caller then uses taskkill. + public static bool KillTree(Process process) + { + if (process == null) { return false; } + TreeJob j; + if (!_treeJobs.TryGetValue(process, out j)) { return false; } + bool added = false, ended = false; + try + { + j.DangerousAddRef(ref added); + ended = TerminateJobObject(j.DangerousGetHandle(), 1); + } + catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead + finally { if (added) { j.DangerousRelease(); } } + // The tree is gone: its job's handle can go now rather than with the Process. + if (ended) { ReleaseTree(process); } + return ended; + } + + // Closes the program's tree job: KillTree can't reach its tree after this. + public static void ReleaseTree(Process process) + { + if (process == null) { return; } + TreeJob j; + if (_treeJobs.TryGetValue(process, out j)) { _treeJobs.Remove(process); j.Dispose(); } + } + + // Harness only: whether the program has a tree job. + public static bool TestHasTree(Process process) + { + TreeJob j; + return process != null && _treeJobs.TryGetValue(process, out j); + } + // Never closed: Windows closes it when this process exits, and that is // what kills the children. private static IntPtr _job = IntPtr.Zero; @@ -501,15 +565,23 @@ public static class PkChildProcessJob } // Never throws: a failed assignment only loses the force-kill cleanup - // for that one process. + // for that one process. Once it's in the kit's job, it also gets a tree + // job (Windows nests it); without one, a kill uses taskkill. public static bool Assign(System.Diagnostics.Process process) { if (_job == IntPtr.Zero || process == null) { return false; } try { - if (AssignProcessToJobObject(_job, process.Handle)) { return true; } - LastError = Marshal.GetLastWin32Error(); - return false; + if (!AssignProcessToJobObject(_job, process.Handle)) { LastError = Marshal.GetLastWin32Error(); return false; } + if (!TestNoTreeJob) + { + IntPtr treeJob = CreateJobObject(IntPtr.Zero, null); + if (treeJob != IntPtr.Zero) + { + if (AssignProcessToJobObject(treeJob, process.Handle)) { AddTree(process, treeJob); } else { CloseHandle(treeJob); } + } + } + return true; } catch { return false; } } @@ -687,6 +759,22 @@ public static class PkChildProcessJob } } + // The start's two attributes: the handles the child inherits and its + // jobs. 0, or the Win32 error (the list is then left uninitialized). + private static int SetStartAttributes(IntPtr attrList, IntPtr attrSize, IntPtr handleArr, int handleCount, IntPtr jobArr, int jobCount) + { + IntPtr size = attrSize; + if (!InitializeProcThreadAttributeList(attrList, 2, 0, ref size)) { return Marshal.GetLastWin32Error(); } + if (UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleArr, (IntPtr)(IntPtr.Size * handleCount), IntPtr.Zero, IntPtr.Zero) + && UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, jobArr, (IntPtr)(IntPtr.Size * jobCount), IntPtr.Zero, IntPtr.Zero)) + { + return 0; + } + int e = Marshal.GetLastWin32Error(); + DeleteProcThreadAttributeList(attrList); + return e; + } + // How TryStart holds .NET's start lock ("Monitor:" or // "Lock:"), or null when it can't and the kit uses Process.Start. public static string StartLockKind { get { StartLock l = GetStartLock(); return l == null ? null : l.Kind; } } @@ -765,7 +853,9 @@ public static class PkChildProcessJob StringBuilder commandLine = BuildCommandLine(fileName, arguments); IntPtr outRead = IntPtr.Zero, outWrite = IntPtr.Zero, errRead = IntPtr.Zero, errWrite = IntPtr.Zero; - IntPtr attrList = IntPtr.Zero, handleArr = IntPtr.Zero, jobArr = IntPtr.Zero; + IntPtr attrList = IntPtr.Zero, handleArr = IntPtr.Zero, jobArr = IntPtr.Zero, treeJob = IntPtr.Zero; + IntPtr attrSize = IntPtr.Zero; + int handleCount = 0, jobCount = 0; bool attrReady = false, created = false, setupFailed = false; IntPtr stdin = IntPtr.Zero; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); @@ -789,26 +879,25 @@ public static class PkChildProcessJob uint hflags; bool stdinInherit = stdin != IntPtr.Zero && stdin != new IntPtr(-1) && GetHandleInformation(stdin, out hflags) && (hflags & HANDLE_FLAG_INHERIT) != 0; - int handleCount = stdinInherit ? 3 : 2; + handleCount = stdinInherit ? 3 : 2; handleArr = Marshal.AllocHGlobal(IntPtr.Size * handleCount); Marshal.WriteIntPtr(handleArr, 0, outWrite); Marshal.WriteIntPtr(handleArr, IntPtr.Size, errWrite); if (stdinInherit) { Marshal.WriteIntPtr(handleArr, 2 * IntPtr.Size, stdin); } - jobArr = Marshal.AllocHGlobal(IntPtr.Size); + // The kit's job, then the program's tree job, which Windows + // nests in it. No tree job if it can't be made: a kill + // then uses taskkill. + if (!TestNoTreeJob) { treeJob = CreateJobObject(IntPtr.Zero, null); } + jobCount = treeJob != IntPtr.Zero ? 2 : 1; + jobArr = Marshal.AllocHGlobal(IntPtr.Size * 2); Marshal.WriteIntPtr(jobArr, _job); + if (jobCount == 2) { Marshal.WriteIntPtr(jobArr, IntPtr.Size, treeJob); } - IntPtr size = IntPtr.Zero; - InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref size); // fails by design: returns the size - attrList = Marshal.AllocHGlobal(size); - if (!InitializeProcThreadAttributeList(attrList, 2, 0, ref size)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } + InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref attrSize); // fails by design: returns the size + attrList = Marshal.AllocHGlobal(attrSize); + int attrError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount); + if (attrError != 0) { throw new Win32Exception(attrError); } attrReady = true; - if (!UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleArr, - (IntPtr)(IntPtr.Size * handleCount), IntPtr.Zero, IntPtr.Zero) - || !UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, jobArr, - (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } if (TestFailSetup) { throw new Win32Exception(5); } } catch (Win32Exception e) @@ -830,10 +919,22 @@ public static class PkChildProcessJob // the program is in the job already, so nothing can escape. uint flags = CREATE_NO_WINDOW | CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT; string dir = String.IsNullOrEmpty(workingDirectory) ? null : workingDirectory; - if (!CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi)) + bool started = !TestRefuseTreeJob || jobCount == 1; + if (started) { started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi); } + if (!started && jobCount == 2) { - throw new Win32Exception(Marshal.GetLastWin32Error()); + // Once more without the tree job, in case that's what Windows + // refused (nesting it): the program still starts, and a kill + // then uses taskkill. A program that can't start at all fails + // again, with its own error. + DeleteProcThreadAttributeList(attrList); attrReady = false; + CloseHandle(treeJob); treeJob = IntPtr.Zero; jobCount = 1; + int retryError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount); + if (retryError != 0) { throw new Win32Exception(retryError); } + attrReady = true; + started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi); } + if (!started) { throw new Win32Exception(Marshal.GetLastWin32Error()); } created = true; } finally @@ -850,6 +951,7 @@ public static class PkChildProcessJob { if (outRead != IntPtr.Zero) { CloseHandle(outRead); } if (errRead != IntPtr.Zero) { CloseHandle(errRead); } + if (treeJob != IntPtr.Zero) { CloseHandle(treeJob); treeJob = IntPtr.Zero; } } } } @@ -882,9 +984,11 @@ public static class PkChildProcessJob if (stderrReader != null) { stderrReader.Dispose(); } if (errSafe != null) { errSafe.Dispose(); } else { CloseHandle(errRead); } CloseHandle(pi.hThread); CloseHandle(pi.hProcess); + if (treeJob != IntPtr.Zero) { CloseHandle(treeJob); } if (proc != null) { proc.Dispose(); } throw; } + if (treeJob != IntPtr.Zero) { AddTree(proc, treeJob); } CloseHandle(pi.hThread); CloseHandle(pi.hProcess); @@ -901,7 +1005,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 10) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 11) { 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." } @@ -1626,10 +1730,14 @@ function Stop-PkProcessTree { # .SYNOPSIS # Kills one or more programs and every program they started. # .DESCRIPTION - # Uses taskkill /T, in as few calls as Windows' command-line limit allows, - # so none is left running and holding a program's output open. If taskkill - # can't start, fails, or is still running after 10 seconds (it's killed - # then), each program is killed directly. + # A program the kit started is killed through its own Job Object, with + # everything it started, even a child whose parent has already exited, so + # none is left running and holding its output open. Any other program, one + # without such a job (StartMode NoJob, or Windows refused it), or one + # Windows won't end that way goes to taskkill /T, which misses a child + # whose parent has exited, in as few calls as Windows' command-line limit + # allows; if taskkill can't start, fails, or is still running after 10 + # seconds (it's killed then), each program is killed directly. # .PARAMETER Process # The program(s), such as the Proc that Start-PkProcess returns. # .OUTPUTS @@ -1661,12 +1769,18 @@ function Stop-PkProcessTreeCore { foreach ($p in $Process) { if ($null -ne $p -and $p.HasExited -eq $false -and $null -ne $p.Id) { $alive.Add($p) } } if ($alive.Count -eq 0) { return $false } $killed = $false + # A program the kit started has a tree job: killing that ends the program + # and everything it started at once, a child whose parent already exited + # included. taskkill /T only finds children through their parent, so it's + # for the rest: a program without a tree job, or one Windows wouldn't end. + $viaTaskkill = [System.Collections.Generic.List[System.Diagnostics.Process]]::new() + foreach ($p in $alive) { if ([PkChildProcessJob]::KillTree($p)) { $killed = $true } else { $viaTaskkill.Add($p) } } # One command line for every PID passes Windows' 32,767-character limit at # roughly 2,500-3,000 programs, and then taskkill can't start at all: so as # many taskkill calls as the limit needs. if ($MaxArgumentLength -le 0) { $MaxArgumentLength = 32000 - $TaskkillPath.Length } - $ids = [int[]]@(foreach ($p in $alive) { $p.Id }) - foreach ($taskkillArgs in (Split-PkTaskkillArguments -Ids $ids -MaxLength $MaxArgumentLength)) { + $ids = [int[]]@(foreach ($p in $viaTaskkill) { $p.Id }) + foreach ($taskkillArgs in $(if ($ids.Count -gt 0) { Split-PkTaskkillArguments -Ids $ids -MaxLength $MaxArgumentLength })) { $psi = [System.Diagnostics.ProcessStartInfo]::new($TaskkillPath, $taskkillArgs) $psi.UseShellExecute = $false $psi.CreateNoWindow = $true @@ -1983,6 +2097,9 @@ function Complete-PkProcess { $result.ExitCode = $Job['Proc'].ExitCode # The program's end, not the output's: before Dispose, which loses it. $result.Duration = Get-PkProcessDuration -Process $Job['Proc'] + # The program has exited: its tree job's handle can go. Anything it left + # running stays in the kit's job, as before. + if ($Job['Proc'] -is [System.Diagnostics.Process]) { [PkChildProcessJob]::ReleaseTree($Job['Proc']) } if ($Dispose) { $Job['Proc'].Dispose() } return [pscustomobject]$result } diff --git a/README.md b/README.md index 9f95dc4..d0a5f4f 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ To leave any callback early, use `return`. PowerShell sends a `continue` or `bre | `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. | | `Complete-PkProcess -Job` | Collect exit code and output from a finished one (`-Job` is what `Start-PkProcess` returned). Same result as `Invoke-PkProcessWithTimeout`. | -| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started, with `taskkill` (as few calls as Windows' command-line limit allows). For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. | +| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started. A program the kit started is killed through its own Job Object, which also reaches a child whose parent has already exited; anything else goes to `taskkill /T` (as few calls as Windows' command-line limit allows). For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. | `Invoke-PkProcessWithTimeout` and `Start-PkProcess` also take `-WorkingDirectory`. @@ -418,7 +418,7 @@ The ones in this README: the engines, the [single-process functions](#single-pro **Does a program I start get my Ctrl+C too?** -No. Programs start without a window, in a hidden console of their own, so Ctrl+C in your window never reaches them. That's what lets them finish while the kit drains. When it does need to stop one (a timeout, or an abort's force-stop), the kit kills it along with anything it started. +No. Programs start without a window, in a hidden console of their own, so Ctrl+C in your window never reaches them. That's what lets them finish while the kit drains. When it does need to stop one (a timeout, or an abort's force-stop), the kit kills it along with anything it started, through a Job Object of the program's own, so even a child whose parent has already exited goes with it. **Was this written by AI?**