From 85d6b5731457be83fcecd6e5a5686cdfc7fe146c Mon Sep 17 00:00:00 2001 From: "577732344@qq.com" <577732344@qq.com> Date: Wed, 24 Sep 2025 11:22:01 +0800 Subject: [PATCH] sh update --- buildAndStart.sh | 80 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 60 insertions(+), 20 deletions(-) diff --git a/buildAndStart.sh b/buildAndStart.sh index 676aa0b..26f111a 100644 --- a/buildAndStart.sh +++ b/buildAndStart.sh @@ -32,37 +32,77 @@ __red() { } __kill() { - local process_name=$1 - PID=$(ps -ef | grep "${process_name}.jar" | grep -v grep | awk '{print $2}' | xargs) + local jar_path="$1" local sleep_seconds=10 local cur_sleep_second=1 + local pids=() - if [[ -z "$PID" ]]; then - __green "进程 ${process_name} 未运行" + # 使用临时文件或直接遍历 jps 输出(避免进程替换) + jps -l 2>/dev/null | while read -r pid main_class; do + if [ "$main_class" = "$jar_path" ]; then + echo "$pid" + fi + done > /tmp/ruoyi_pids.$$ + + # 读取匹配的 PID 到数组(在当前 shell 中) + while IFS= read -r pid; do + [ -n "$pid" ] && pids+=("$pid") + done < /tmp/ruoyi_pids.$$ + + # 清理临时文件 + rm -f /tmp/ruoyi_pids.$$ + + if [ ${#pids[@]} -eq 0 ]; then + __green "未找到运行中的进程: $jar_path" return 0 fi - while [[ -n "$PID" && "$sleep_seconds" -ge "$cur_sleep_second" ]]; do - __green "尝试kill PID: ${PID}" + __green "找到 ${#pids[@]} 个匹配进程: ${pids[*]}" - if [ "$sleep_seconds" -eq "$cur_sleep_second" ]; then - __red "强制关闭: ${cur_sleep_second}" - kill -9 $PID >> /dev/null 2>&1 - else - kill $PID >> /dev/null 2>&1 - fi - - __green "停止程序计时: ${cur_sleep_second}秒" - sleep 1 - cur_sleep_second="$(_math "$cur_sleep_second" + 1)" - PID=$(ps -ef | grep "${process_name}.jar" | grep -v grep | awk '{print $2}' | xargs) + # 发送 SIGTERM + for pid in "${pids[@]}"; do + __green "发送 SIGTERM 到 PID: $pid" + kill "$pid" >/dev/null 2>&1 done - if [[ -n "$PID" ]]; then - __red "无法停止进程 ${process_name}, PID: ${PID}" + # 等待退出 + while [ $cur_sleep_second -le $sleep_seconds ]; do + remaining=() + for pid in "${pids[@]}"; do + if kill -0 "$pid" 2>/dev/null; then + remaining+=("$pid") + fi + done + + if [ ${#remaining[@]} -eq 0 ]; then + __green "所有进程已成功停止" + return 0 + fi + + __green "等待进程退出... (${cur_sleep_second}/${sleep_seconds} 秒)" + sleep 1 + cur_sleep_second=$((cur_sleep_second + 1)) + done + + # 强制 kill -9 + __red "优雅关闭超时,强制终止剩余进程: ${remaining[*]}" + for pid in "${remaining[@]}"; do + kill -9 "$pid" 2>/dev/null + done + + # 检查是否还有存活 + still_alive=() + for pid in "${remaining[@]}"; do + if kill -0 "$pid" 2>/dev/null; then + still_alive+=("$pid") + fi + done + + if [ ${#still_alive[@]} -gt 0 ]; then + __red "无法终止进程: ${still_alive[*]}" return 1 else - __green "进程 ${process_name} 已成功停止" + __green "所有进程已强制终止" return 0 fi }