chore: startup script with port detection and auto-cleanup
./start.sh: 1. Detect if port 8888 is in use → kill gracefully, force if needed 2. Verify port free, rebuild if source changed, start in background 3. Wait up to 10s for readiness confirmation
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
# exchange-monitor 启动脚本
|
||||
# 自动检测端口占用并清理旧进程
|
||||
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
PORT=8888
|
||||
BIN="./exchange-monitor"
|
||||
LOG="exchange-monitor.log"
|
||||
|
||||
# 检查端口占用,释放旧进程
|
||||
PID=$(ss -tlnp 2>/dev/null | grep ":$PORT " | sed -n 's/.*pid=\([0-9]*\).*/\1/p')
|
||||
if [ -n "$PID" ]; then
|
||||
echo "[start] Port $PORT 被 PID=$PID 占用,尝试优雅停止..."
|
||||
kill "$PID" 2>/dev/null || true
|
||||
sleep 1
|
||||
# 强制清理
|
||||
if kill -0 "$PID" 2>/dev/null; then
|
||||
echo "[start] 强制终止 PID=$PID..."
|
||||
kill -9 "$PID" 2>/dev/null || true
|
||||
sleep 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 确认端口空闲
|
||||
if ss -tlnp 2>/dev/null | grep -q ":$PORT "; then
|
||||
echo "[start] ERROR: 端口 $PORT 仍被占用,放弃启动"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 编译(如果源码有变更)
|
||||
if [ ! -x "$BIN" ] || [ "$(find . -name '*.go' -newer "$BIN" 2>/dev/null | head -1)" ]; then
|
||||
echo "[start] 编译新二进制..."
|
||||
go build -o "$BIN" . 2>&1
|
||||
fi
|
||||
|
||||
# 启动
|
||||
echo "[start] 启动 exchange-monitor (端口 $PORT)..."
|
||||
nohup "$BIN" >> "$LOG" 2>&1 &
|
||||
PID=$!
|
||||
echo "[start] PID=$PID"
|
||||
|
||||
# 等待就绪
|
||||
for i in $(seq 1 10); do
|
||||
if ss -tlnp 2>/dev/null | grep -q ":$PORT "; then
|
||||
echo "[start] 就绪 (${i}s)"
|
||||
echo "[start] http://localhost:$PORT"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "[start] 启动超时(10s),请检查日志: tail -f $LOG"
|
||||
exit 1
|
||||
Reference in New Issue
Block a user