Ubuntu18.04系統(tǒng)如何后臺運行程序
在Ubuntu18.04系統(tǒng)中,有時我們需要讓程序在后臺持續(xù)運行,而不受終端關(guān)閉或用戶注銷的影響。本文將介紹幾種實現(xiàn)后臺運行程序的方法。
使用&符號
最簡單的方法是在命令后面加上&符號,如:
command &
這樣程序會在后臺運行,但當(dāng)用戶退出終端時,程序可能會被終止。
nohup命令
使用nohup命令可以讓程序忽略掛起信號,實現(xiàn)持續(xù)運行:
nohup command &
程序的輸出會被重定向到nohup.out文件中。
screen工具
screen是一個強大的終端復(fù)用工具,可以創(chuàng)建虛擬終端來運行程序:
- 安裝screen:
sudo apt install screen
- 創(chuàng)建新會話:
screen -S session_name
- 在新會話中運行程序
- 按Ctrl+A,然后按D detach會話
- 重新連接會話:
screen -r session_name
tmux工具
tmux是另一個終端復(fù)用工具,用法類似screen:
- 安裝tmux:
sudo apt install tmux
- 創(chuàng)建新會話:
tmux new -s session_name
- 在新會話中運行程序
- 按Ctrl+B,然后按D detach會話
- 重新連接會話:
tmux attach -t session_name
systemd服務(wù)
對于需要長期運行的程序,可以創(chuàng)建systemd服務(wù):
- 創(chuàng)建服務(wù)文件:
sudo nano /etc/systemd/system/myapp.service
- 編寫服務(wù)配置
- 重新加載systemd:
sudo systemctl daemon-reload
- 啟動服務(wù):
sudo systemctl start myapp
- 設(shè)置開機自啟:
sudo systemctl enable myapp
通過以上方法,您可以根據(jù)需求選擇合適的方式在Ubuntu18.04系統(tǒng)中實現(xiàn)程序的后臺運行。不同方法各有優(yōu)缺點,建議根據(jù)實際情況選擇最適合的方式。