Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux nohup 命令詳解:後台持久運行、輸出重導向與 Session 斷開保護

編輯:關於 Linux

nohup(No Hang UP)讓程式忽略 SIGHUP 訊號,在終端關閉、SSH 斷線後持續運行。本文涵蓋基本用法、輸出處理、常見坑(關閉終端方式)、jobs/fg/bg 作業控制與替代方案。

基本語法

nohup 命令 [參數] &
  • & 放入背景執行
  • 標準輸出/錯誤自動導向 nohup.out(當前目錄或 $HOME)

典型場景

1. 一般腳本持久化

nohup /root/test.php &

提示 appending output to nohup.out,輸出記錄於 nohup.out。

2. 自訂輸出檔

nohup command > myout.file 2>&1 &

3. 避開「關閉終端即中斷」陷阱

錯誤做法:執行 nohup ... & 後直接點視窗關閉按鈕(X)。
正確做法:見到提示後,按任意鍵回到 Shell 提示符,輸入 exit 正常登出。
原因:直接關視窗會發送 SIGHUP 給前景 Shell,導致其子進程(含 nohup 進程)被清理;exit 則正常釋放 Session。

作業控制速查

命令說明
jobs列出背景/暫停作業
fg %n將作業 n 調至前景
bg %n將暫停作業 n 放入背景繼續
Ctrl+Z暫停前景作業
Ctrl+C終止前景作業
kill %n終止作業 n

jobs 輸出中 + 表示預設作業(fg/bg 不加參數操作的對象),- 表示次預設。

替代方案

  • screen / tmux:虛擬終端,可隨時重掛,功能更強
  • systemd-run --user --scope command:現代 systemd 方式
  • disown -h %n:將作業從 Shell 作業表移除,不再接收 SIGHUP

輸出檔管理

  • nohup.out 會無限增長,建議定期清理或用 logrotate
  • 生產環境建議明確導向專用日誌檔而非依賴預設

掌握 nohup 正確用法與作業控制,是 Linux 遠端運維長時間任務的基礎技能。

Copyright © Windows教程網 All Rights Reserved