Created
February 25, 2021 09:15
-
-
Save Gardelll/40a119c7af5045d15e0685e595a0242d to your computer and use it in GitHub Desktop.
jar 启动jio本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# arg $1: 退出值 | |
# arg $2: 错误信息 | |
function exit_msg() { | |
[[ $2 != "" ]] && echo "$2" 1>&2 | |
exit "$1" | |
} | |
# arg $1: 进程 pid | |
function isRunning() { | |
ps -p "$1" &>/dev/null | |
} | |
# arg $1: 程序文件 | |
# arg $2: 进程名 | |
# arg $3: pid 文件 | |
# arg $4: 日志文件 | |
function runDaemon() { | |
EXEC="$(basename "$JAR_FILE")" | |
start-stop-daemon --start --quiet \ | |
--exec "$EXEC" \ | |
--make-pidfile --pidfile "$PID_FILE" \ | |
--background --no-close \ | |
--startas "$(which java)" \ | |
--chdir "$(dirname "$JAR_FILE")" \ | |
-- -jar -Xmx200M "$EXEC" "${@}" \ | |
>>"$LOG_FILE" 2>&1 || exit_msg 10 | |
} | |
function stopPidFile() { | |
[[ -f "$PID_FILE" ]] || return 0 | |
pid=$(cat "$PID_FILE") | |
isRunning "$pid" || { | |
echo "未运行 (process ${pid}). 删除 pid 文件" 1>&2 | |
rm -f "$PID_FILE" | |
return 0 | |
} | |
kill "$pid" &>/dev/null || { | |
echo "无法停止进程 $pid" 1>&2 | |
return 1 | |
} | |
for ((i = 1; i <= 5; i++)); do | |
isRunning "$pid" || { | |
echo "已结束 [$pid]" | |
rm -f "$PID_FILE" | |
return 0 | |
} | |
[[ $i -eq 3 ]] && kill "$pid" &>/dev/null | |
sleep 1 | |
done | |
echo "无法停止进程 $pid" 1>&2 | |
return 1 | |
} | |
function runJar() { | |
echo "后台运行:$JAR_FILE" | |
if [[ -f "$PID_FILE" ]]; then | |
pid=$(cat "$PID_FILE") | |
if [[ $(isRunning "$pid") && 'true' != "$RESTART" ]]; then | |
echo "Already running [$pid]" 1>&2 | |
return 1 | |
fi | |
stopPidFile "$PID_FILE" || return 1 | |
fi | |
runDaemon "$@" | |
return $? | |
} | |
JAR_FILE="$1" | |
PID_FILE="${JAR_FILE}.pid" | |
LOG_FILE="${JAR_FILE}.log" | |
CMD="$2" | |
RESTART="$3" | |
[ -f "$JAR_FILE" ] || exit_msg 1 "找不到 jar 文件" | |
case "$CMD" in | |
'start') | |
runJar "${@:5}" | |
exit $? | |
;; | |
'stop') | |
stopPidFile | |
exit $? | |
;; | |
*) | |
exit_msg 2 "未知命令, Usage: $0 /path/to/jar [start|stop] [true|false]" | |
;; | |
esac | |
# 用法:./jar_start_wrapper.sh [jar 路径] [启动或停止,start|stop] [是否重启,true|false] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment