1.后台運行 並將日志輸出到指定文件
nohup java -jar Sjzh-1.0.jar > sjzh.log 2>&1 &
Log.log ” 該命令就是指定日志輸出的文件
&代表讓該命令在后台執行即使terminal(終端)關閉
">>"表示將輸出以追加的方式重定向到Log.log中
標准輸出文件(stdout):stdout 的文件描述符為1,Unix程序默認向stdout輸出數據。
標准錯誤文件(stderr):stderr的文件描述符為2,Unix程序會向stderr流中寫入錯誤信息。
“> Log.log 2>&1” :表示將 stdout 和 stderr 合並后重定向到 Log.log
nohup java -jar pgcz.jar --spring.profiles.active=test -Dspring.config.location=application-test.yml >nohup.out 2>&1 &
- setsid java -jar qjtb.jar
setsid是用來保證當用戶注銷(logout)或者網絡斷開時當前啟動的子進程不會被關閉,從而就可以一直運行
3.腳本方式 與jar包同一路徑
vim boot.sh
#!/usr/bin/env bash
APP_NAME=$1
# 使用說明,用來提示輸入參數
usage() {
echo "Usage: sh boot [APP_NAME] [start|stop|restart|status]"
exit 1
}
# 檢查程序是否在運行
is_exist(){
# 獲取PID
PID=$(ps -ef |grep ${APP_NAME} | grep -v $0 |grep -v grep |awk '{print $2}')
# -z "${pid}"判斷pid是否存在,如果不存在返回1,存在返回0
if [[ -z "${PID}" ]]; then
# 如果進程不存在返回1
return 1
else
# 進程存在返回0
return 0
fi
}
# 定義啟動程序函數
start(){
is_exist
if [[ $? -eq "0" ]]; then
echo "${APP_NAME} is already running, PID=${PID}"
else
nohup java -jar ${APP_NAME} >/dev/null 2>&1 &
PID=$(echo $!)
echo "${APP_NAME} start success, PID=$!"
fi
}
# 停止進程函數
stop(){
is_exist
if [[ $? -eq "0" ]]; then
kill -9 ${PID}
echo "${APP_NAME} process stop, PID=${PID}"
else
echo "There is not the process of ${APP_NAME}"
fi
}
# 重啟進程函數
restart(){
stop
start
}
# 查看進程狀態
status(){
is_exist
if [[ $? -eq "0" ]]; then
echo "${APP_NAME} is running, PID=${PID}"
else
echo "There is not the process of ${APP_NAME}"
fi
}
case $2 in
"start")
start
;;
"stop")
stop
;;
"restart")
restart
;;
"status")
status
;;
*)
usage
;;
esac
exit 0
運行命令
./boot.sh Sjzh-1.0.jar stop --停止
./boot.sh Sjzh-1.0.jar start --啟動
./boot.sh Sjzh-1.0.jar status --狀態
./boot.sh Sjzh-1.0.jar restart --重啟