Linux系統中我們經常需要將應用或程序放在后臺運行,下面從應用角度介紹下后臺運行的三板斧supervisor、screen、nohup。
為什么要先介紹supervisor呢?
因為supervisor可以對所管理的進程啟動、重載、停止,當監測到進程停止后,會自動拉起,實現了進程的“故障自愈”。我們不需要再額外開發守護腳本,導致維護成本的增加。
docker運行命令、對于運維這簡直是神器,必須放在第一位,但是需要花點配置成本。下面就來看下supervisor如何使用。
1.安裝
#centos7yum install supervisorvim /etc/supervisord.conf#最后兩行可看到,最終配置文件在 supervisord.d/目錄下[include]files = supervisord.d/*.ini#開機自啟動systemctl enable supervisord#查看是否開機自啟動systemctl is-enabled supervisord
2.配置
3.管理
#參數可以為all或單個項目hellosupervisorctl reload [all | hello]#更新配置文件,更新配置文件并重啟與更新有關的進程supervisorctl update hello#重載配置文件 ,注意reload會導致supervisor重啟,所管理的進程會重啟supervisorctl reload hello#查看狀態supervisorctl status#啟動hellosupervisorctl start hello
LINUX教程,4.應用場景
supervisor適用于可多次啟動并長期運行的后臺任務,如java服務、緩存服務及其他自定義服務等。
5.小結
supervisor可以很優雅的解決掉關于進程的啟動、重啟、重載等方面的操作,而之前我們可能需要花更多的時間去額外處理,如判斷進程存在、殺掉進程甚至可能還需要配合腳本寫個循環去串聯這些操作。
另supervisor還提供了很多第三方的Web-UI統一的 WebUI 集中化管理各個服務器節點的進程,如CeSi、supervisor-easy、Supervisord-monitor等,在此不多做描述。
注意:
shell進程、Screen的會話保持特性,即screen打開的會話可以分離或恢復,而不影響會話內部的操作,這樣我們將命令行、腳本甚至是數據傳輸放到screen會話中運行,效果就類似于后臺運行。
1.普通模式
[root@test #]$ yum install screen -y#創建會話hello,此時會登入新會話[root@test #]$ screen或[root@test #]$ screen -S hello#分離會話,此時程序不會中斷鍵盤ctrl+a+d 分離會話[detached from 28877.hello]#列出所有會話[root@test #]$ screen -lsThere is a screen on: 28877.hello (Detached) 28876.test (Dead)1 Socket in /var/run/screen/S-root.#恢復會話[root@test #]$ screen -r 28877或[root@test #]$ screen -r hello#清除dead會話[root@test #]$ screen -wipe
2.分離模式
在分離模式下的屏幕會話,作為守護程序啟動。
#創建一個后臺運行任務[root@test #]$ vim test.sh#!/bin/bashn=0while [ $n -le 50 ]do echo $n n=$(( $n + 1 )) sleep 1done#創建處于分離模式的會話,啟動后直接斷開會話[root@test #]$ screen -dmS test./test.sh#此時會話已斷開,但是任務仍在運行,相當于把任務放在后臺運行[root@test #]$ screen -lsThere is a screen on: 30537.test (Detached)#登入會話腳本正在會話中打印輸出,執行完畢后會會話終止[root@test #]$ screen -r 30537012
注意:
如果要打印screen日志,需如下設置:
#其中%t 為標題,如screen_test.logecho "logfile /root/screen_%t.log" >> /etc/screenrc#-L 打開日志輸出#-t 為標題#執行命令后,會在/root下生成screen_test.logscreen -L -t test -dmS test ./test.sh
linux文件權限。3.應用場景
screen適用于單次長時間運行的任務,如備份、ftp傳輸、下載、數據導入導出、終端超時斷開等。
4.小結
screen的會話保持和日志輸出,在一定程度上也可以作為后臺運行的一種方式。但是需要多用戶會話的管理,如test用戶創建的會話,root通過screen -ls查看是看不到test用戶新建的會話的。因此會話管理,一定需要頭腦清醒。
nohup后臺運行最常見的方式,拿來即用,沒有什么配置成本,可直接上手。這個大家比較熟悉,就不作過多介紹。
#還是以上面的test.sh腳本為例[root@test #]$ vim test.sh#!/bin/bashn=0while [ $n -le 50 ]do echo $n n=$(( $n + 1 )) sleep 1done#默認情況下nohup運行的程序,輸出記錄會打印到當前目錄下的nohup.out文件中[root@test #]$ nohup bash test.sh &[1] 7415nohup: ignoring input and appending output to ‘nohup.out’[root@test #]$ tail -f nohup.out012[root@test #]$ jobs -l[1]+ 7415 Running nohup bash test.sh 標準輸出及錯誤輸出,重定向到自定義日志[root@test #]$ nohup bash test.sh > test.log 2>&1 &[root@test #]$ tail -f test.lognohup: ignoring input01
以上三種后臺運行的方式,大家可各取所需,不必矯枉過正,畢竟我們首先要保證的是業務穩定運行。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态