預設情況下,關閉終端機會發送 SIGHUP 信號給該終端機啟動的所有子進程,導致後台程式終止。使用 nohup 可免疫掛斷信號。
nohup 命令 [參數...] &
nohup:忽略 SIGHUP (No Hang UP)&:放入背景執行 (job control)nohup.out (當前目錄)# 執行測試腳本
nohup ./test.sh &
# 輸出:[1] 12345
# nohup: ignoring input and appending output to 'nohup.out'
# 指定輸出檔案
nohup ./test.sh > mylog.log 2>&1 &
# 執行 Python 腳本
nohup python3 server.py &
# 執行 Java 應用
nohup java -jar app.jar --server.port=8080 &
jobs -l
# [1]+ 12345 Running nohup ./test.sh &
# 1. 執行中按 Ctrl+Z 暫停
# 2. bg %1 放入背景繼續
# 3. disown -h %1 免疫 SIGHUP (相當於 nohup)
# Systemd 服務單元 /etc/systemd/system/myapp.service
[Unit]
Description=My App
After=network.target
[Service]
Type=simple
User=www
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 server.py
Restart=on-failure
RestartSec=5
StandardOutput=append:/var/log/myapp.log
StandardError=append:/var/log/myapp.err
[Install]
WantedBy=multi-user.target
# 啟用
systemctl daemon-reload
systemctl enable --now myapp
screen / tmux:虛擬終端機,可離線重接setsid:在新會話中執行systemd-run --user --scope:用戶級服務nohup cmd & 後關閉終端機,**不影響** 已啟動進程</dev/nullnohup 不改變進程的 nice 值或 CPU 親和性