"""Process-tree pause/resume helpers shared by the desktop and Web UI.""" from __future__ import annotations import os import subprocess def _run_powershell_tree_action(pid: int, action: str) -> None: if action not in {"suspend", "resume"}: raise ValueError(f"unsupported process action: {action}") native_call = "[NativeMethods]::SuspendProcess($_)" if action == "suspend" else "[NativeMethods]::ResumeProcess($_)" script = f""" $ErrorActionPreference = 'Stop' Add-Type @" using System; using System.Runtime.InteropServices; public static class NativeMethods {{ [DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr OpenProcess(uint access, bool inherit, int pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr handle); [DllImport("ntdll.dll")] public static extern int NtSuspendProcess(IntPtr processHandle); [DllImport("ntdll.dll")] public static extern int NtResumeProcess(IntPtr processHandle); public static void SuspendProcess(int pid) {{ IntPtr h = OpenProcess(0x0800, false, pid); if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid); try {{ int rc = NtSuspendProcess(h); if (rc != 0) throw new InvalidOperationException("NtSuspendProcess failed: " + rc); }} finally {{ CloseHandle(h); }} }} public static void ResumeProcess(int pid) {{ IntPtr h = OpenProcess(0x0800, false, pid); if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid); try {{ int rc = NtResumeProcess(h); if (rc != 0) throw new InvalidOperationException("NtResumeProcess failed: " + rc); }} finally {{ CloseHandle(h); }} }} }} "@ $ids = New-Object System.Collections.Generic.List[int] function Add-Tree([int]$p) {{ if ($ids.Contains($p)) {{ return }} $ids.Add($p) | Out-Null Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" | ForEach-Object {{ Add-Tree ([int]$_.ProcessId) }} }} Add-Tree {int(pid)} $ids | Sort-Object -Unique | ForEach-Object {{ {native_call} }} """ proc = subprocess.run( ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=8, check=False, ) if proc.returncode != 0: detail = (proc.stderr or proc.stdout or "").strip() raise RuntimeError(detail or f"{action} failed for pid={pid}") def suspend_process_tree(pid: int) -> None: """Pause a process and its children.""" pid = int(pid or 0) if pid <= 0: raise ValueError("missing pid") if os.name == "nt": _run_powershell_tree_action(pid, "suspend") return import signal os.kill(pid, signal.SIGSTOP) def resume_process_tree(pid: int) -> None: """Resume a process and its children.""" pid = int(pid or 0) if pid <= 0: raise ValueError("missing pid") if os.name == "nt": _run_powershell_tree_action(pid, "resume") return import signal os.kill(pid, signal.SIGCONT)