編碼的世界 / 優質文選 / 感情

Linux(CentOS7)後台運行程序關掉窗口不被殺掉


2022年5月17日
-   

目錄

前言: 下面操作都是基於 CentOS7 操作的
後台運行命令
  • nohup 執行腳本或者執行命令 > 日志的輸出路徑 &

注意:日志文件不需要提前創建(自動創建),但是目錄一定是存在的目錄才行(不會自動創建)
腳本執行
# 創建 app.jar.sh 文件並寫入命令
echo "java -jar app.jar" >> app.jar.sh
# 執行腳本
nohup ./app.jar.sh > app.jar.log &
# 如果報沒有權限就加上 bash
[root@VM-0-5-centos temp]# nohup: ignoring input and redirecting stderr to stdout
nohup: failed to run command ‘./app.jar.sh’: Permission denied
[1]+ Exit 126 nohup ./app.jar.sh > app.sh.log
# 加上bash執行腳本, 看到輸出pid就成功了, 然後按回車就行
nohup bash ./app.jar.sh > app.sh.logs &

命令執行
# 輸出日志到當前目錄的 app.jar.log 文件 (日志文件不需要提前創建),執行完之後直接按回車就行
nohup java -jar app.jar > app.jar.log &
# 把日志輸出到 home 目錄下的 app.jar.log
nohup java -jar app.jar > /home/app.jar.log &
###################執行過程###################
[root@VM-0-5-centos temp]# nohup java -jar app.jar > app.jar.log &
[1] 1690 # 進程id
[root@VM-0-5-centos temp]# nohup: ignoring input and redirecting stderr to stdout
# 查看所有的java進程,1690就是剛才後台運行的java服務
[root@VM-0-5-centos temp]# ps -aux|grep java
root 1690 100 11.4 2530680 214908 pts/0 Sl 11:05 0:16 java -jar app.jar
root 1769 0.0 0.0 112708 976 pts/0 S+ 11:06 0:00 grep color=auto java
# 殺掉剛才啟動的java後台進程
[root@VM-0-5-centos temp]# kill 1690

監控產生的日志文件
# tail -f 日志文件
tail -f app.jar.log

查看所有後台進程
# 查看所有進程
ps -aux
# 查看指定進程
ps -aux|grep xxx
# 查看端口是否被占用
netstat -anp|grep 端口號
netstat -anp|grep 7078

結束進程
kill pid
# 結束進程id為1690的進程
kill 1690

根據進程id查看程序啟動路徑
命令:ls -l /proc/進程id
# 查看進程
[root@localhost ~]# ps -ef|grep nginx
root 7622 31541 0 15:24 pts/1 00:00:00 grep color=auto nginx
nobody 13138 13609 0 5▒▒07 ? 00:00:56 nginx: worker process
root 13609 1 0 5▒▒06 ? 00:00:00 nginx: master process ./nginx
# 根據進程id查看進程信息
[root@localhost ~]#ls -l /proc/13609

熱門文章