要讓一支腳本在背景長期執行、掛掉還能自己爬起來,Ubuntu 上最省事的做法是搭配
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 -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 的優點是夠小夠直接,適合臨時把一支腳本丟到背景跑。