Files
hair/stop_worker.sh
2026-06-16 21:16:44 +08:00

46 lines
1.1 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# 停止 GPU worker(由 run_worker.sh 后台启动的进程)。
# 优先用 worker.pid;找不到则按端口兜底查找。
set -euo pipefail
cd "$(dirname "$0")"
PID_FILE="worker.pid"
PORT="${PORT:-8187}"
stop_pid() {
local pid="$1"
if kill -0 "$pid" 2>/dev/null; then
echo ">> 停止 worker (PID $pid)"
kill "$pid"
# 等待优雅退出,最多 10 秒
for _ in $(seq 1 10); do
kill -0 "$pid" 2>/dev/null || return 0
sleep 1
done
echo ">> 未在 10 秒内退出,强制 kill -9"
kill -9 "$pid" 2>/dev/null || true
fi
}
# 1) 用 PID 文件
if [ -f "$PID_FILE" ]; then
PID="$(cat "$PID_FILE")"
if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
stop_pid "$PID"
rm -f "$PID_FILE"
echo ">> 已停止"
exit 0
fi
rm -f "$PID_FILE"
fi
# 2) 兜底:按监听端口查找
PIDS="$(ss -tlnp 2>/dev/null | grep ":${PORT} " | grep -oE 'pid=[0-9]+' | grep -oE '[0-9]+' | sort -u || true)"
if [ -n "$PIDS" ]; then
for p in $PIDS; do stop_pid "$p"; done
echo ">> 已停止(按端口 ${PORT} 查找)"
exit 0
fi
echo ">> 没有发现正在运行的 worker(端口 ${PORT}"