
在 Raspberry PI(運行 raspbian)上我需要執行腳本關閉/關機, 但不在重新啟動時。
我的第一次嘗試是定義一個服務,如下所示:
[Unit]
Description=Power off service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/usr/local/bin/poweroff.sh
[Install]
WantedBy=multi-user.target
這有效,但腳本也在重新啟動時運行。所以我嘗試將其安裝到不同的目標:
[Install]
WantedBy=shutdown.target halt.target
但經過此更改後,該腳本根本無法運作。
定義關閉時應執行的操作的正確方法是什麼?
答案1
根據我在網路上收集的信息,最好的選擇是放在Conflicts=reboot.target
單元檔案([Unit]
部分)中,然後在腳本中執行以下命令:
systemctl list-jobs | egrep -q 'reboot.target.*start'
如果reboot.target
計劃啟動,則重新啟動。否則就不是了。如果命令“成功”,則係統正在重新啟動。否則,它就會關閉。你可以這樣使用它:
if ! systemctl list-jobs | egrep -q 'reboot.target.*start'; then
echo Shutting down
fi
答案2
丹尼爾的回答解決了問題中的問題。但它仍然不完全是我所需要的:腳本調用得太早,我需要它盡可能晚地執行(腳本實際上使用連接到 RPi 引腳的繼電器關閉電源GPIO
)
投入更多時間後,我找到了更簡單的解決方案,它正是我想要的:
/etc/systemd/system/systemd-poweroff.service.d
如果目錄尚不存在則建立poweroff.conf
在目錄中建立一個新檔案/etc/systemd/system/systemd-poweroff.service.d
:
[Service]
ExecStartPre=/usr/local/bin/poweroff.sh
透過這種方法,無需添加新服務