oclaw/runtime/operations/scripts/stop_gateway.ps1
oliver b6dd8edc5d 优化 gateway 停止脚本在 PID 已退出场景下的日志表现。
在 stop_gateway 的进程终止流程中先检测进程是否存在,避免误报 Failed to stop 警告,保留端口回退清理逻辑并让 stop_all 输出更稳定可读。

Made-with: Cursor
2026-04-29 01:20:58 +08:00

78 lines
2.2 KiB
PowerShell

param(
[int]$Port = 8787,
[switch]$Force = $false
)
$ErrorActionPreference = "Stop"
function Write-Step([string]$msg) {
Write-Host "==> $msg" -ForegroundColor Cyan
}
function Warn([string]$msg) {
Write-Host "[WARN] $msg" -ForegroundColor Yellow
}
function Kill-ProcId([int]$procId) {
$exists = $null
try {
$exists = Get-Process -Id $procId -ErrorAction SilentlyContinue
} catch {
$exists = $null
}
if (-not $exists) {
Write-Host "PID=$procId already exited" -ForegroundColor DarkGray
return $true
}
try {
Stop-Process -Id $procId -Force
Write-Host "Stopped PID=$procId" -ForegroundColor Green
return $true
} catch {
Warn "Failed to stop PID=$procId : $($_.Exception.Message)"
return $false
}
}
$runDir = Join-Path $PSScriptRoot ".run"
$pidFile = Join-Path $runDir "gateway.pid"
Write-Step "Stopping gateway"
if (Test-Path $pidFile) {
$raw = (Get-Content $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
$procId = 0
[void][int]::TryParse([string]$raw, [ref]$procId)
if ($procId -gt 0) {
$ok = Kill-ProcId -procId $procId
if ($ok) {
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
# Keep going to also clean up any orphan listeners on $Port.
} else {
# Stale pid file is common after crashes; fall back to stop-by-port.
if ($Force) {
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
} else {
Warn "PID file kill failed; falling back to stop-by-port. Re-run with -Force to also clear pid file."
}
}
}
}
Write-Step "No PID file; attempting to stop by port $Port"
try {
$conns = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if (-not $conns) {
Warn "No listener found on port $Port"
exit 0
}
$pids = $conns | Select-Object -ExpandProperty OwningProcess -Unique
foreach ($p in $pids) {
if ($p -gt 0) { [void](Kill-ProcId -procId $p) }
}
exit 0
} catch {
Warn "Stop by port failed: $($_.Exception.Message)"
if (-not $Force) { exit 1 }
}