萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 終端機關閉後保持後台程式持續執行:nohup 實戰指南

預設情況下,關閉終端機會發送 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 &

將前台任務轉背景並免疫 SIGHUP

# 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 & 後關閉終端機,**不影響** 已啟動進程
  • 但若進程嘗試讀取 stdin,會收到 EOF 錯誤,建議重導向 </dev/null
  • nohup 不改變進程的 nice 值或 CPU 親和性
copyright © 萬盛學電腦網 all rights reserved