
我正在使用 Debian Stretch 和 systemd 版本 231-9。
即使我登出時,我也需要在背景執行一些 shell 腳本和非守護程式。
我曾經使用LSB 標頭製作簡單的init.d 腳本,然後使用啟動選項來簡單地執行“my_script.sh >> /var/log/my_script.log 2>&1 &”以在後台運行my_script.sh,但現在Systemd一旦我關閉終端,無論我嘗試什麼,都會殺死它們:&、nohup、setsid、disown。
您能幫我提供一個正確的 init.d 腳本的配方,使任何腳本或非守護程序程序作為守護程序運行嗎?
謝謝。
答案1
如果您的東西由 root 使用者擁有,那麼/etc/rc.local
:
screen -dmS ThingOne /path/to/thing-one
screen -dmS ThingTwo /path/to/thing-two
或者,對於任何使用者(包括 root),在 cron 表中:
@reboot screen -dmS ThingOne /path/to/thing-one
# et cetera
答案2
這是將腳本設定為守護進程的方法:
#! /bin/sh
### BEGIN INIT INFO
# Provides: foobar
# Required-Start: $local_fs $network
# Required-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: foobar
# Description: more foo for your bars
### END INIT INFO
# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting foobar "
# example 1 - system service
# /usr/bin/foobar --config /etc/foo.conf start
# example 2 - run script as user
# su --login mkaz --command "/home/mkaz/bin/my-script --cmd-args"
;;
stop)
echo "Stopping foobar"
# example 1
# /usr/bin/foobar --config /etc/foo.conf stop
;;
*)
echo "Usage: /etc/init.d/foobar {start|stop}"
exit 1
;;
esac
exit 0
然後將腳本移至 init.d 資料夾並將其設定為可執行文件
sudo mv foobar /etc/init.d/ # move to init.d
sudo chmod 755 /etc/init.d/foobar # make executable
如果您想在啟動時啟動腳本:
update-rc.d foobar defaults
如果您想從啟動中刪除腳本:
update-rc.d -f foobar remove
如果您想手動啟動腳本:
service foobar start
來源 :https://debian-administration.org/article/28/Making_scripts_run_at_boot_time_with_Debian