Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

讓 Linux 程式以服務方式背景運行,崩潰後自動重啟

要讓一支腳本在背景長期執行、掛掉還能自己爬起來,Ubuntu 上最省事的做法是搭配

daemon
這個小工具。

安裝 daemon

apt-get install daemon

裝好之後它會落在

/usr/bin/daemon
。

準備測試腳本

#!/bin/bash
echo $(date) " Starting Script" >> /tmp/output
while true
do
    echo $(date) >> /tmp/output
    sleep 5
done

用 daemon 拉起並自動守護

daemon -r /root/test.sh

執行後你會看到背景有兩個進程:

[root@terminal40162 ~] ps -ef | grep test
root 11421     1  0 14:11 ? 00:00:00 daemon -r /root/test.sh
root 11422 11421  0 14:11 ? 00:00:00 /bin/bash /root/test.sh

父進程是 daemon,子進程才是腳本本身。手動

kill 11422
之後,那支 bash 馬上又冒出來——這就是 daemon 在背景監視的效果,
-r
代表持續重啟。

做成服務並設定開機自啟

把控制邏輯寫成

/etc/init.d/testd
後即可用標準方式操作:

service testd start
service testd stop
service testd restart

CentOS 系列可用 chkconfig 加入開機啟動:

chkconfig --add testd
chkconfig --list testd
# testd 0:off 1:off 2:on 3:on 4:on 5:on 6:off

Ubuntu 沒有 chkconfig,手動建立連結即可:

ln -s /etc/init.d/testd /etc/rc0.d/S0test
ln -s /etc/init.d/testd /etc/rc1.d/S0test
ln -s /etc/init.d/testd /etc/rc2.d/S0test
ln -s /etc/init.d/testd /etc/rc3.d/S0test
ln -s /etc/init.d/testd /etc/rc4.d/S0test
ln -s /etc/init.d/testd /etc/rc5.d/S0test
ln -s /etc/init.d/testd /etc/rc6.d/S0test

重啟 Ubuntu 後確認服務已自行啟動:

root@dns066:~# service testd status
daemon: TEST is running (pid 1106)

更現代的替代方案

若系統使用 systemd(Ubuntu 16.04 之後、CentOS 7 之後),更推薦寫一個 unit 檔,用

Restart=always
取代 daemon 的守護角色,再用
systemctl enable
處理開機自啟。 supervise 系列(supervisord、runit)也是常見選擇。daemon 的優點是夠小夠直接,適合臨時把一支腳本丟到背景跑。

Copyright © Linux教程網 All Rights Reserved