#!/usr/bin/env bash # ============================================================================ # run_web.sh —— 后台启动网页上位机(教材演示用) # # 用法: # bash scripts/run_web.sh # 默认 127.0.0.1:8088 # bash scripts/run_web.sh 9000 # 指定端口 # bash scripts/run_web.sh 8088 data # 指定端口与数据目录 # 停止: bash scripts/stop_web.sh # ============================================================================ set -uo pipefail PORT="${1:-8088}" DATA_DIR="${2:-data}" cd "$(dirname "$0")/.." || exit 1 BIN="build/debug/smart_home" if [ ! -x "$BIN" ]; then echo "未找到 $BIN,先构建:cmake --preset debug && cmake --build build/debug -j" exit 1 fi # 端口占用检查:先礼后兵(避免把别人的服务顶掉) if command -v ss >/dev/null 2>&1 && ss -ltn 2>/dev/null | grep -q ":${PORT} "; then echo "端口 ${PORT} 已被占用,请换一个端口:bash scripts/run_web.sh 8090" ss -ltnp 2>/dev/null | grep ":${PORT} " || true exit 1 fi mkdir -p "$DATA_DIR" logs LOG="logs/web_${PORT}.log" PIDFILE="logs/web_${PORT}.pid" nohup "$BIN" --web --port "$PORT" --data "$(pwd)/$DATA_DIR" >"$LOG" 2>&1 & PID=$! echo "$PID" >"$PIDFILE" # 就绪探测(最多 3 秒) for _ in 1 2 3 4 5 6 7 8 9 10 11 12; do if curl -s -m 1 -o /dev/null --noproxy '*' "http://127.0.0.1:${PORT}/"; then break fi sleep 0.25 done if curl -s -m 2 -o /dev/null --noproxy '*' "http://127.0.0.1:${PORT}/"; then echo "网页上位机已启动:http://127.0.0.1:${PORT}/" echo " PID :$PID(记录于 $PIDFILE)" echo " 日志 :$LOG" echo " 数据目录 :$(pwd)/$DATA_DIR" echo " 停止 :bash scripts/stop_web.sh ${PORT}" else echo "启动失败,日志尾部:" tail -n 20 "$LOG" exit 1 fi