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、&、setsid、disown、screen 多種方式與作業控制

編輯:Linux 教學

長時間運算程式必須在背景穩定執行,不受 SSH 斷線影響。本文比較五種背景執行方式與作業控制指令。

一、基本背景執行 &

./program > output.log 2>&1 &
  • 輸出導向檔案,背景執行。
  • 缺點:Shell 退出會送 SIGHUP 終止子程序。

二、nohup 免疫 SIGHUP

nohup ./program > output.log 2>&1 &
  • 忽略掛起信號,Shell 退出程式仍存活。
  • 輸出預設導向 nohup.out,可自行導向。

三、setsid 脫離終端會話

setsid ./program > output.log 2>&1 &
  • 建立新會話,父進程變為 init (PID 1),完全脫離控制終端。

四、disown 移除殭屍作業

./program > output.log 2>&1 &
disown -h %1   # %1 為 jobs 號碼
  • 將作業從 Shell 作業表移除,不再接收 SIGHUP。

五、subshell 括號法

(./program > output.log 2>&1 &)
  • 在子 Shell 執行,同樣脫離父 Shell 生命週期。

六、screen / tmux 終端多工器 (最推薦)

# 建立離線 session
screen -dmS mysession
# 重新連接
screen -r mysession
# 在 session 內執行任意程式,關閉視窗不影響
  • 支援多視窗、分割、捲動歷史、多人共享。
  • 適合需互動、多指令連續執行的場景。

七、作業控制速查

指令功能
jobs -l列出背景作業與 PID
fg %n將作業 n 切回前景
bg %n將暫停作業 n 切回背景
Ctrl+Z暫停前景作業
Ctrl+C終止前景作業

選擇建議

  • 單一指令、無互動:nohup 或 setsid。
  • 需互動、多步驟、長期維護:screen / tmux。
  • 已在前景執行想丟背景:Ctrl+Z → bg → disown -h %n。

善用背景執行技巧,讓長跑任務不再因斷線而前功盡棄。

Copyright © Windows教程網 All Rights Reserved